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