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",
|
49
|
722 xreal,
|
|
723 ]
|
|
724 else:
|
50
|
725 cll = ["planemo", "test", "--galaxy_python_version",
|
|
726 "3.6", "--galaxy_root",
|
|
727 self.args.galaxy_root,
|
|
728 xreal,]
|
|
729 p = subprocess.run(
|
|
730 cll, shell=True, cwd=self.tooloutdir, stderr=tout, stdout=tout
|
|
731 )
|
|
732 if genoutputs:
|
|
733 with os.scandir(self.testdir) as outs:
|
|
734 for entry in outs:
|
|
735 if entry.is_file():
|
|
736 dest = os.path.join(self.repdir, entry.name)
|
|
737 src = os.path.join(self.testdir, entry.name)
|
|
738 shutil.copyfile(src, dest)
|
|
739 tout.write(
|
|
740 "Copied output %s to %s after planemo test\n" % (src, dest)
|
|
741 )
|
49
|
742 tout.close()
|
48
|
743 return p.returncode
|
|
744
|
|
745 def eph_galaxy_load(self):
|
50
|
746 """load the new tool from the local toolshed after planemo uploads it
|
48
|
747 """
|
49
|
748 if os.path.exists(self.tlog):
|
50
|
749 tout = open(self.tlog, "a")
|
49
|
750 else:
|
50
|
751 tout = open(self.tlog, "w")
|
49
|
752 cll = [
|
|
753 "shed-tools",
|
|
754 "install",
|
|
755 "-g",
|
|
756 self.args.galaxy_url,
|
|
757 "--latest",
|
|
758 "-a",
|
|
759 self.args.galaxy_api_key,
|
|
760 "--name",
|
|
761 self.args.tool_name,
|
|
762 "--owner",
|
|
763 "fubar",
|
|
764 "--toolshed",
|
|
765 self.args.toolshed_url,
|
|
766 "--section_label",
|
|
767 "Generated Tools",
|
51
|
768
|
49
|
769 ]
|
|
770 print("running\n", " ".join(cll))
|
|
771 p = subprocess.run(cll, shell=False, stderr=tout, stdout=tout)
|
48
|
772 if p.returncode != 0:
|
49
|
773 print(
|
|
774 "Repository %s installation returned %d"
|
|
775 % (self.args.tool_name, p.returncode)
|
|
776 )
|
48
|
777 else:
|
49
|
778 print("installed %s" % self.args.tool_name)
|
|
779 tout.close()
|
48
|
780 return p.returncode
|
|
781
|
|
782 def writeShedyml(self):
|
50
|
783 """for planemo
|
|
784 """
|
49
|
785 yuser = self.args.user_email.split("@")[0]
|
|
786 yfname = os.path.join(self.tooloutdir, ".shed.yml")
|
|
787 yamlf = open(yfname, "w")
|
|
788 odict = {
|
|
789 "name": self.tool_name,
|
|
790 "owner": yuser,
|
|
791 "type": "unrestricted",
|
|
792 "description": self.args.tool_desc,
|
50
|
793 "synopsis": self.args.tool_desc,
|
|
794 "category": "TF Generated Tools",
|
49
|
795 }
|
48
|
796 yaml.dump(odict, yamlf, allow_unicode=True)
|
|
797 yamlf.close()
|
|
798
|
50
|
799 def makeTool(self):
|
|
800 """write xmls and input samples into place
|
|
801 """
|
|
802 self.makeXML()
|
|
803 if self.args.script_path:
|
|
804 stname = os.path.join(self.tooloutdir, "%s" % (self.sfile))
|
|
805 if not os.path.exists(stname):
|
|
806 shutil.copyfile(self.sfile, stname)
|
|
807 xreal = "%s.xml" % self.tool_name
|
|
808 xout = os.path.join(self.tooloutdir, xreal)
|
|
809 shutil.copyfile(xreal, xout)
|
|
810 for p in self.infiles:
|
|
811 pth = p[IPATHPOS]
|
|
812 dest = os.path.join(self.testdir, "%s_sample" % p[ICLPOS])
|
|
813 shutil.copyfile(pth, dest)
|
|
814 dest = os.path.join(self.repdir, "%s.%s" % (p[ICLPOS], p[IFMTPOS]))
|
|
815 shutil.copyfile(pth, dest)
|
49
|
816
|
50
|
817 def makeToolTar(self):
|
|
818 """ move outputs into test-data and prepare the tarball
|
|
819 """
|
|
820 for p in self.outfiles:
|
|
821 src = p[ONAMEPOS]
|
|
822 if os.path.isfile(src):
|
|
823 dest = os.path.join(self.testdir, "%s_sample" % src)
|
|
824 shutil.copyfile(src, dest)
|
|
825 dest = os.path.join(self.repdir, "%s.%s" % (src, p[OFMTPOS]))
|
|
826 shutil.copyfile(src, dest)
|
|
827 else:
|
|
828 print(
|
|
829 "### problem - output file %s not found in tooloutdir %s"
|
|
830 % (src, self.tooloutdir)
|
|
831 )
|
|
832 self.newtarpath = "toolfactory_%s.tgz" % self.tool_name
|
|
833 tf = tarfile.open(self.newtarpath, "w:gz")
|
|
834 tf.add(name=self.tooloutdir, arcname=self.tool_name)
|
|
835 tf.close()
|
|
836 shutil.copyfile(self.newtarpath, self.args.new_tool)
|
|
837
|
|
838 def moveRunOutputs(self):
|
|
839 """need to move planemo or run outputs into toolfactory collection
|
|
840 """
|
|
841 with os.scandir(self.tooloutdir) as outs:
|
|
842 for entry in outs:
|
|
843 if not entry.is_file() or entry.name.startswith("."):
|
|
844 continue
|
|
845 if "." in entry.name:
|
|
846 nayme, ext = os.path.splitext(entry.name)
|
|
847 else:
|
|
848 ext = ".txt"
|
|
849 ofn = "%s%s" % (entry.name.replace(".", "_"), ext)
|
|
850 dest = os.path.join(self.repdir, ofn)
|
|
851 src = os.path.join(self.tooloutdir, entry.name)
|
|
852 shutil.copyfile(src, dest)
|
|
853
|
49
|
854
|
48
|
855 def main():
|
|
856 """
|
|
857 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
49
|
858 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath"
|
|
859 --tool_name "foo" --interpreter "Rscript"
|
48
|
860 </command>
|
|
861 """
|
|
862 parser = argparse.ArgumentParser()
|
|
863 a = parser.add_argument
|
49
|
864 a("--script_path", default=None)
|
|
865 a("--history_test", default=None)
|
|
866 a("--cl_prefix", default=None)
|
|
867 a("--sysexe", default=None)
|
|
868 a("--packages", default=None)
|
48
|
869 a("--tool_name", default=None)
|
|
870 a("--input_files", default=[], action="append")
|
|
871 a("--output_files", default=[], action="append")
|
|
872 a("--user_email", default="Unknown")
|
|
873 a("--bad_user", default=None)
|
49
|
874 a("--make_Tool", default="runonly")
|
48
|
875 a("--help_text", default=None)
|
|
876 a("--tool_desc", default=None)
|
|
877 a("--tool_version", default=None)
|
|
878 a("--citations", default=None)
|
49
|
879 a("--command_override", default=None)
|
|
880 a("--test_override", default=None)
|
48
|
881 a("--additional_parameters", action="append", default=[])
|
|
882 a("--edit_additional_parameters", action="store_true", default=False)
|
|
883 a("--parampass", default="positional")
|
|
884 a("--tfout", default="./tfout")
|
|
885 a("--new_tool", default="new_tool")
|
|
886 a("--runmode", default=None)
|
49
|
887 a("--galaxy_url", default="http://localhost:8080")
|
50
|
888 a("--galaxy_api_key", default="fakekey")
|
48
|
889 a("--toolshed_url", default="http://localhost:9009")
|
50
|
890 a("--toolshed_api_key", default="fakekey")
|
|
891 a("--galaxy_root", default="/galaxy-central")
|
48
|
892
|
|
893 args = parser.parse_args()
|
|
894 assert not args.bad_user, (
|
|
895 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to "admin_users" in the Galaxy configuration file'
|
|
896 % (args.bad_user, args.bad_user)
|
|
897 )
|
49
|
898 assert args.tool_name, "## Tool Factory expects a tool name - eg --tool_name=DESeq"
|
48
|
899 assert (
|
49
|
900 args.sysexe or args.packages
|
48
|
901 ), "## Tool Factory wrapper expects an interpreter or an executable package"
|
49
|
902 args.input_files = [x.replace('"', "").replace("'", "") for x in args.input_files]
|
48
|
903 # remove quotes we need to deal with spaces in CL params
|
|
904 for i, x in enumerate(args.additional_parameters):
|
49
|
905 args.additional_parameters[i] = args.additional_parameters[i].replace('"', "")
|
48
|
906 r = ScriptRunner(args)
|
49
|
907 r.writeShedyml()
|
|
908 r.makeTool()
|
50
|
909 if args.command_override or args.test_override:
|
|
910 retcode = r.planemo_test(genoutputs=True) # this fails :( - see PR
|
|
911 r.moveRunOutputs()
|
|
912 r.makeToolTar()
|
|
913 retcode = r.planemo_test(genoutputs=False)
|
|
914 r.moveRunOutputs()
|
|
915 if args.make_Tool == "gentestinstall":
|
|
916 r.planemo_shedload()
|
|
917 r.eph_galaxy_load()
|
|
918 else:
|
49
|
919 retcode = r.run()
|
|
920 if retcode:
|
|
921 sys.stderr.write(
|
|
922 "## Run failed with return code %d. Cannot build yet. Please fix and retry"
|
|
923 % retcode
|
|
924 )
|
|
925 sys.exit(1)
|
|
926 else:
|
|
927 r.moveRunOutputs()
|
50
|
928 r.makeToolTar()
|
|
929 if args.make_Tool in ["gentestinstall", "gentest"]:
|
|
930 r.planemo_test(genoutputs=False)
|
|
931 r.moveRunOutputs()
|
|
932 if args.make_Tool == "gentestinstall":
|
|
933 r.planemo_shedload()
|
|
934 r.eph_galaxy_load()
|
48
|
935
|
|
936
|
|
937 if __name__ == "__main__":
|
|
938 main()
|