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