13
|
1 # rgToolFactoryMultIn.py
|
|
2 # see https://bitbucket.org/fubar/galaxytoolfactory/wiki/Home
|
|
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 https://bitbucket.org/fubar/galaxytoolfactory/wiki/Home
|
|
9 #
|
|
10 # January 2015
|
|
11 # in the process of building a complex tool
|
|
12 # added ability to choose one of the current toolshed package_r or package_perl or package_python dependencies and source that package
|
14
|
13 # add that package to tool_dependencies
|
|
14 # Note that once the generated tool is loaded, it will have that package's env.sh loaded automagically so there is no
|
|
15 # --envshpath in the parameters for the generated tool and it uses the system one which will be first on the adjusted path.
|
13
|
16 #
|
|
17 # sept 2014 added additional params from
|
|
18 # https://bitbucket.org/mvdbeek/dockertoolfactory/src/d4863bcf7b521532c7e8c61b6333840ba5393f73/DockerToolFactory.py?at=default
|
|
19 # passing them is complex
|
|
20 # and they are restricted to NOT contain commas or double quotes to ensure that they can be safely passed together on
|
|
21 # the toolfactory command line as a comma delimited double quoted string for parsing and passing to the script
|
|
22 # see examples on this tool form
|
|
23
|
|
24 # august 2014
|
|
25
|
|
26 # Allows arbitrary number of input files
|
|
27 # NOTE positional parameters are now passed to script
|
|
28 # and output (may be "None") is *before* arbitrary number of inputs
|
|
29 #
|
|
30 # march 2014
|
|
31 # had to remove dependencies because cross toolshed dependencies are not possible - can't pre-specify a toolshed url for graphicsmagick and ghostscript
|
|
32 # grrrrr - night before a demo
|
|
33 # added dependencies to a tool_dependencies.xml if html page generated so generated tool is properly portable
|
|
34 #
|
|
35 # added ghostscript and graphicsmagick as dependencies
|
|
36 # fixed a wierd problem where gs was trying to use the new_files_path from universe (database/tmp) as ./database/tmp
|
|
37 # errors ensued
|
|
38 #
|
|
39 # august 2013
|
|
40 # found a problem with GS if $TMP or $TEMP missing - now inject /tmp and warn
|
|
41 #
|
|
42 # july 2013
|
|
43 # added ability to combine images and individual log files into html output
|
|
44 # just make sure there's a log file foo.log and it will be output
|
|
45 # together with all images named like "foo_*.pdf
|
|
46 # otherwise old format for html
|
|
47 #
|
|
48 # January 2013
|
|
49 # problem pointed out by Carlos Borroto
|
|
50 # added escaping for <>$ - thought I did that ages ago...
|
|
51 #
|
|
52 # August 11 2012
|
|
53 # changed to use shell=False and cl as a sequence
|
|
54
|
|
55 # This is a Galaxy tool factory for simple scripts in python, R or whatever ails ye.
|
|
56 # It also serves as the wrapper for the new tool.
|
|
57 #
|
|
58 # you paste and run your script
|
|
59 # Only works for simple scripts that read one input from the history.
|
|
60 # Optionally can write one new history dataset,
|
|
61 # and optionally collect any number of outputs into links on an autogenerated HTML page.
|
|
62
|
|
63 # DO NOT install on a public or important site - please.
|
|
64
|
|
65 # installed generated tools are fine if the script is safe.
|
|
66 # They just run normally and their user cannot do anything unusually insecure
|
|
67 # but please, practice safe toolshed.
|
|
68 # Read the fucking code before you install any tool
|
|
69 # especially this one
|
|
70
|
|
71 # After you get the script working on some test data, you can
|
|
72 # optionally generate a toolshed compatible gzip file
|
|
73 # containing your script safely wrapped as an ordinary Galaxy script in your local toolshed for
|
|
74 # safe and largely automated installation in a production Galaxy.
|
|
75
|
|
76 # If you opt for an HTML output, you get all the script outputs arranged
|
|
77 # as a single Html history item - all output files are linked, thumbnails for all the pdfs.
|
|
78 # Ugly but really inexpensive.
|
|
79 #
|
|
80 # Patches appreciated please.
|
|
81 #
|
|
82 #
|
|
83 # long route to June 2012 product
|
|
84 # Behold the awesome power of Galaxy and the toolshed with the tool factory to bind them
|
|
85 # derived from an integrated script model
|
|
86 # called rgBaseScriptWrapper.py
|
|
87 # Note to the unwary:
|
|
88 # This tool allows arbitrary scripting on your Galaxy as the Galaxy user
|
|
89 # There is nothing stopping a malicious user doing whatever they choose
|
|
90 # Extremely dangerous!!
|
|
91 # Totally insecure. So, trusted users only
|
|
92 #
|
|
93 # preferred model is a developer using their throw away workstation instance - ie a private site.
|
|
94 # no real risk. The universe_wsgi.ini admin_users string is checked - only admin users are permitted to run this tool.
|
|
95 #
|
|
96
|
|
97 import sys
|
|
98 import shutil
|
|
99 import subprocess
|
|
100 import os
|
|
101 import time
|
|
102 import tempfile
|
|
103 import optparse
|
|
104 import tarfile
|
|
105 import re
|
|
106 import shutil
|
|
107 import math
|
|
108
|
|
109 progname = os.path.split(sys.argv[0])[1]
|
|
110 myversion = 'V001.1 March 2014'
|
|
111 verbose = False
|
|
112 debug = False
|
|
113 toolFactoryURL = 'https://bitbucket.org/fubar/galaxytoolfactory'
|
|
114
|
|
115 # if we do html we need these dependencies specified in a tool_dependencies.xml file and referred to in the generated
|
|
116 # tool xml
|
|
117
|
|
118 def timenow():
|
|
119 """return current time as a string
|
|
120 """
|
|
121 return time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(time.time()))
|
|
122
|
|
123 html_escape_table = {
|
|
124 "&": "&",
|
|
125 ">": ">",
|
|
126 "<": "<",
|
|
127 "$": "\$"
|
|
128 }
|
|
129
|
|
130 def html_escape(text):
|
|
131 """Produce entities within text."""
|
|
132 return "".join(html_escape_table.get(c,c) for c in text)
|
|
133
|
|
134
|
|
135 def html_unescape(text):
|
|
136 """Revert entities within text."""
|
|
137 t = text.replace('&','&').replace('>','>').replace('<','<').replace('\$','$')
|
|
138 return t
|
|
139
|
|
140 def cmd_exists(cmd):
|
|
141 return subprocess.call("type " + cmd, shell=True,
|
|
142 stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
|
|
143
|
|
144 def parse_citations(citations_text):
|
|
145 """
|
|
146 """
|
|
147 citations = [c for c in citations_text.split("**ENTRY**") if c.strip()]
|
|
148 citation_tuples = []
|
|
149 for citation in citations:
|
|
150 if citation.startswith("doi"):
|
|
151 citation_tuples.append( ("doi", citation[len("doi"):].strip() ) )
|
|
152 else:
|
|
153 citation_tuples.append( ("bibtex", citation[len("bibtex"):].strip() ) )
|
|
154 return citation_tuples
|
|
155
|
|
156 def shell_source(script):
|
|
157 """need a way to source a Galaxy tool interpreter env.sh so we can use that dependency
|
|
158 package
|
|
159 see http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html
|
|
160 Sometime you want to emulate the action of "source" in bash,
|
|
161 settings some environment variables. Here is a way to do it.
|
|
162 Note that we have to finesse the automagic exports using nulls as newlines for env"""
|
|
163 pipe = subprocess.Popen("env -i ; . %s ; env -0" % script, stdout=subprocess.PIPE, shell=True)
|
|
164 output = pipe.communicate()[0]
|
|
165 outl = output.split('\0')
|
|
166 outl = [x for x in outl if len(x.split("=")) == 2]
|
|
167 newenv = dict((line.split("=", 1) for line in outl))
|
|
168 os.environ.update(newenv)
|
|
169
|
|
170 class ScriptRunner:
|
|
171 """class is a wrapper for an arbitrary script
|
|
172 note funky templating. this should all be done proper.
|
|
173 Problem is, this kludge developed quite naturally and seems to work ok with
|
|
174 little overhead...
|
|
175
|
|
176 """
|
|
177
|
|
178
|
|
179 def __init__(self,opts=None,treatbashSpecial=True):
|
|
180 """
|
|
181 cleanup inputs, setup some outputs
|
|
182
|
|
183 """
|
|
184
|
|
185 self.toolhtmldepinterpskel = """<?xml version="1.0"?>
|
|
186 <tool_dependency>
|
|
187 <package name="ghostscript" version="9.10">
|
|
188 <repository name="package_ghostscript_9_10" owner="devteam" prior_installation_required="True" />
|
|
189 </package>
|
|
190 <package name="graphicsmagick" version="1.3.18">
|
|
191 <repository name="package_graphicsmagick_1_3" owner="iuc" prior_installation_required="True" />
|
|
192 </package>
|
|
193 <package name="%(interpreter_name)s" version="%(interpreter_version)s">
|
|
194 <repository name="%(interpreter_pack)s" owner="%(interpreter_owner)s" prior_installation_required="True" />
|
|
195 </package>
|
|
196
|
|
197 <readme>
|
|
198 %(readme)s
|
14
|
199 This file was autogenerated by the Galaxy Tool Factory 2
|
13
|
200 </readme>
|
|
201 </tool_dependency>
|
|
202 """
|
|
203
|
|
204 self.toolhtmldepskel = """<?xml version="1.0"?>
|
|
205 <tool_dependency>
|
|
206 <package name="ghostscript" version="9.10">
|
|
207 <repository name="package_ghostscript_9_10" owner="devteam" prior_installation_required="True" />
|
|
208 </package>
|
|
209 <package name="graphicsmagick" version="1.3.18">
|
|
210 <repository name="package_graphicsmagick_1_3" owner="iuc" prior_installation_required="True" />
|
|
211 </package>
|
|
212 <readme>
|
|
213 %(readme)s
|
14
|
214 This file was autogenerated by the Galaxy Tool Factory 2
|
13
|
215 </readme>
|
|
216 </tool_dependency>
|
|
217 """
|
|
218
|
|
219 self.emptytoolhtmldepskel = """<?xml version="1.0"?>
|
|
220 <tool_dependency>
|
|
221 <readme>
|
|
222 %(readme)s
|
14
|
223 This file was autogenerated by the Galaxy Tool Factory 2
|
13
|
224 </readme>
|
|
225 </tool_dependency>
|
|
226 """
|
|
227
|
|
228 self.protorequirements = """<requirements>
|
|
229 <requirement type="package" version="9.10">ghostscript</requirement>
|
|
230 <requirement type="package" version="1.3.18">graphicsmagick</requirement>
|
|
231 </requirements>"""
|
|
232
|
|
233 self.protorequirements_interpreter = """<requirements>
|
|
234 <requirement type="package" version="9.10">ghostscript</requirement>
|
|
235 <requirement type="package" version="1.3.18">graphicsmagick</requirement>
|
|
236 <requirement type="package" version="%(interpreter_version)s">%(interpreter_name)s</requirement>
|
|
237 </requirements>"""
|
|
238
|
|
239
|
|
240 self.newCommand="""
|
|
241 %(toolname)s.py --script_path "$runMe" --interpreter "%(interpreter)s"
|
|
242 --tool_name "%(toolname)s"
|
|
243 %(command_inputs)s
|
|
244 %(command_outputs)s
|
|
245 """
|
|
246
|
|
247 self.tooltestsTabOnly = """
|
|
248 <test>
|
|
249 %(test1Inputs)s
|
|
250 <param name="job_name" value="test1"/>
|
|
251 <param name="runMe" value="$runMe"/>
|
|
252 <output name="output1="%(test1Output)s" ftype="tabular"/>
|
|
253 %(additionalParams)s
|
|
254 </test>
|
|
255 """
|
|
256
|
|
257 self.tooltestsHTMLOnly = """
|
|
258 <test>
|
|
259 %(test1Inputs)s
|
|
260 <param name="job_name" value="test1"/>
|
|
261 <param name="runMe" value="$runMe"/>
|
|
262 %(additionalParams)s
|
|
263 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="5"/>
|
|
264 </test>
|
|
265 """
|
|
266
|
|
267 self.tooltestsBoth = """
|
|
268 <test>
|
|
269 %(test1Inputs)s
|
|
270 <param name="job_name" value="test1"/>
|
|
271 <param name="runMe" value="$runMe"/>
|
|
272 %(additionalParams)s
|
|
273 <output name="output1" file="%(test1Output)s" ftype="tabular" />
|
|
274 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="10"/>
|
|
275 </test>
|
|
276 """
|
|
277
|
|
278 self.newXML="""<tool id="%(toolid)s" name="%(toolname)s" version="%(tool_version)s">
|
|
279 %(tooldesc)s
|
|
280 %(requirements)s
|
|
281 <command interpreter="python">
|
|
282 %(command)s
|
|
283 </command>
|
|
284 <inputs>
|
|
285 %(inputs)s
|
|
286 %(additionalInputs)s
|
|
287 </inputs>
|
|
288 <outputs>
|
|
289 %(outputs)s
|
|
290 </outputs>
|
|
291 <configfiles>
|
|
292 <configfile name="runMe">
|
|
293 %(script)s
|
|
294 </configfile>
|
|
295 </configfiles>
|
|
296 <tests>
|
|
297 %(tooltests)s
|
|
298 </tests>
|
|
299 <help>
|
|
300
|
|
301 %(help)s
|
|
302
|
14
|
303 This tool was autogenerated from a user provided script using the Galaxy Tool Factory 2
|
|
304 https://toolshed.g2.bx.psu.edu/view/fubar/tool_factory_2
|
13
|
305 </help>
|
|
306 <citations>
|
|
307 %(citations)s
|
|
308 <citation type="doi">10.1093/bioinformatics/bts573</citation>
|
|
309 </citations>
|
|
310 </tool>"""
|
|
311
|
|
312 self.useGM = cmd_exists('gm')
|
|
313 self.useIM = cmd_exists('convert')
|
|
314 self.useGS = cmd_exists('gs')
|
|
315 self.temp_warned = False # we want only one warning if $TMP not set
|
|
316 self.treatbashSpecial = treatbashSpecial
|
|
317 if opts.output_dir: # simplify for the tool tarball
|
|
318 os.chdir(opts.output_dir)
|
|
319 self.thumbformat = 'png'
|
|
320 self.opts = opts
|
|
321 self.toolname = re.sub('[^a-zA-Z0-9_]+', '', opts.tool_name) # a sanitizer now does this but..
|
|
322 self.toolid = self.toolname
|
|
323 self.myname = sys.argv[0] # get our name because we write ourselves out as a tool later
|
|
324 self.pyfile = self.myname # crude but efficient - the cruft won't hurt much
|
|
325 self.xmlfile = '%s.xml' % self.toolname
|
|
326 rx = open(self.opts.script_path,'r').readlines()
|
|
327 rx = [x.rstrip() for x in rx] # remove pesky dos line endings if needed
|
|
328 self.script = '\n'.join(rx)
|
|
329 fhandle,self.sfile = tempfile.mkstemp(prefix=self.toolname,suffix=".%s" % (opts.interpreter))
|
|
330 tscript = open(self.sfile,'w') # use self.sfile as script source for Popen
|
|
331 tscript.write(self.script)
|
|
332 tscript.close()
|
|
333 self.indentedScript = " %s" % '\n'.join([' %s' % html_escape(x) for x in rx]) # for restructured text in help
|
|
334 self.escapedScript = "%s" % '\n'.join([' %s' % html_escape(x) for x in rx])
|
|
335 self.elog = os.path.join(self.opts.output_dir,"%s_error.log" % self.toolname)
|
|
336 if opts.output_dir: # may not want these complexities
|
|
337 self.tlog = os.path.join(self.opts.output_dir,"%s_runner.log" % self.toolname)
|
|
338 art = '%s.%s' % (self.toolname,opts.interpreter)
|
|
339 artpath = os.path.join(self.opts.output_dir,art) # need full path
|
|
340 artifact = open(artpath,'w') # use self.sfile as script source for Popen
|
|
341 artifact.write(self.script)
|
|
342 artifact.close()
|
|
343 self.cl = []
|
|
344 self.html = []
|
|
345 self.test1Inputs = [] # now a list
|
|
346 a = self.cl.append
|
|
347 a(opts.interpreter)
|
|
348 a(self.sfile)
|
|
349 # if multiple inputs - positional or need to distinguish them with cl params
|
|
350 if opts.input_tab:
|
|
351 tests = []
|
|
352 for i,intab in enumerate(opts.input_tab): # if multiple, make tests
|
|
353 if intab.find(',') <> -1:
|
|
354 (gpath,uname) = intab.split(',')
|
|
355 else:
|
|
356 gpath = uname = intab
|
|
357 tests.append(os.path.basename(gpath))
|
|
358 self.test1Inputs = '<param name="input_tab" value="%s" />' % (','.join(tests))
|
|
359 else:
|
|
360 self.test1Inputs = ''
|
|
361 # we always pass path,name pairs in using python optparse append
|
|
362 # but the command line has to be different
|
|
363 self.infile_paths = ''
|
|
364 self.infile_names = ''
|
|
365 if self.opts.input_tab:
|
|
366 self.infile_paths = ','.join([x.split(',')[0].strip() for x in self.opts.input_tab])
|
|
367 self.infile_names = ','.join([x.split(',')[1].strip() for x in self.opts.input_tab])
|
|
368 if self.opts.interpreter == 'python':
|
|
369 # yes, this is how additional parameters are always passed in python - to the TF itself and to
|
|
370 # scripts to avoid having unknown parameter names (yes, they can be parsed but...) on the command line
|
|
371 if self.opts.input_tab:
|
|
372 a('--INPATHS "%s"' % (self.infile_paths))
|
|
373 a('--INNAMES "%s"' % (self.infile_names))
|
|
374 if self.opts.output_tab:
|
|
375 a('--OUTPATH "%s"' % self.opts.output_tab)
|
|
376 for p in opts.additional_parameters:
|
|
377 p = p.replace('"','')
|
|
378 psplit = p.split(',')
|
|
379 param = html_unescape(psplit[0])
|
|
380 value = html_unescape(psplit[1])
|
|
381 a('%s="%s"' % (param,value))
|
|
382 if (self.opts.interpreter == 'Rscript'):
|
|
383 # pass params on command line
|
|
384 if self.opts.input_tab:
|
|
385 a('INPATHS="%s"' % self.infile_paths)
|
|
386 a('INNAMES="%s"' % self.infile_names)
|
|
387 if self.opts.output_tab:
|
|
388 a('OUTPATH="%s"' % self.opts.output_tab)
|
|
389 for p in opts.additional_parameters:
|
|
390 p = p.replace('"','')
|
|
391 psplit = p.split(',')
|
|
392 param = html_unescape(psplit[0])
|
|
393 value = html_unescape(psplit[1])
|
|
394 a('%s="%s"' % (param,value))
|
|
395 if (self.opts.interpreter == 'perl'):
|
|
396 # pass params on command line
|
|
397 if self.opts.input_tab:
|
|
398 a('%s' % self.infile_paths)
|
|
399 a('%s' % self.infile_names)
|
|
400 if self.opts.output_tab:
|
|
401 a('%s' % self.opts.output_tab)
|
|
402 for p in opts.additional_parameters:
|
|
403 p = p.replace('"','')
|
|
404 psplit = p.split(',')
|
|
405 param = html_unescape(psplit[0])
|
|
406 value = html_unescape(psplit[1])
|
|
407 if (value.find(' ') <> -1):
|
|
408 a('%s="%s"' % (param,value))
|
|
409 else:
|
|
410 a('%s=%s' % (param,value))
|
|
411 if self.opts.interpreter == 'sh' or self.opts.interpreter == 'bash':
|
|
412 # more is better - now move all params into environment AND drop on to command line.
|
|
413 self.cl.insert(0,'env')
|
|
414 if self.opts.input_tab:
|
|
415 self.cl.insert(1,'INPATHS=%s' % (self.infile_paths))
|
|
416 self.cl.insert(2,'INNAMES=%s' % (self.infile_names))
|
|
417 if self.opts.output_tab:
|
|
418 self.cl.insert(3,'OUTPATH=%s' % (self.opts.output_tab))
|
|
419 a('OUTPATH=%s' % (self.opts.output_tab))
|
|
420 # sets those environment variables for the script
|
|
421 # additional params appear in CL - yes, it's confusing
|
|
422 for i,p in enumerate(opts.additional_parameters):
|
|
423 psplit = p.split(',')
|
|
424 param = html_unescape(psplit[0])
|
|
425 value = html_unescape(psplit[1])
|
|
426 if (value.find(' ') <> -1):
|
|
427 a('%s="%s"' % (param,value))
|
|
428 self.cl.insert(4+i,'%s="%s"' % (param,value))
|
|
429 else:
|
|
430 a('%s=%s' % (param,value))
|
|
431 self.cl.insert(4+i,'%s=%s' % (param,value))
|
|
432 self.interp_owner = None
|
|
433 self.interp_pack = None
|
|
434 self.interp_revision = None
|
|
435 self.interp_version = None
|
|
436 if opts.envshpath <> 'system': # need to parse out details for our tool_dependency
|
14
|
437 try: # fragile - depends on common naming convention as at jan 2015 = package_[interp]_v0_v1_v2... = version v0.v1.v2.. is in play
|
|
438
|
13
|
439 packdetails = opts.envshpath.split(os.path.sep)[-4:-1] # eg ['fubar', 'package_r_3_1_1', '63cdb9b2234c']
|
|
440 self.interpreter_owner = packdetails[0]
|
|
441 self.interpreter_pack = packdetails[1]
|
|
442 self.interpreter_name = packdetails[1].split('_')[1].upper()
|
|
443 self.interpreter_revision = packdetails[2]
|
14
|
444 self.interpreter_version = '.'.join(packdetails[1].split('_')[2:])
|
13
|
445 except:
|
|
446 pass
|
|
447 self.outFormats = opts.output_format
|
|
448 self.inputFormats = opts.input_formats
|
|
449 self.test1Output = '%s_test1_output.xls' % self.toolname
|
|
450 self.test1HTML = '%s_test1_output.html' % self.toolname
|
|
451
|
|
452 def makeXML(self):
|
|
453 """
|
|
454 Create a Galaxy xml tool wrapper for the new script as a string to write out
|
|
455 fixme - use templating or something less fugly than this example of what we produce
|
|
456
|
|
457 <tool id="reverse" name="reverse" version="0.01">
|
|
458 <description>a tabular file</description>
|
|
459 <command interpreter="python">
|
|
460 reverse.py --script_path "$runMe" --interpreter "python"
|
|
461 --tool_name "reverse" --input_tab "$input1" --output_tab "$output1"
|
|
462 </command>
|
|
463 <inputs>
|
|
464 <param name="input1" type="data" format="tabular" label="Select one or more input files from your history"/>
|
|
465 <param name="job_name" type="text" label="Supply a name for the outputs to remind you what they contain" value="reverse"/>
|
|
466 </inputs>
|
|
467 <outputs>
|
|
468 <data format="tabular" name="output1q" label="${job_name}"/>
|
|
469
|
|
470 </outputs>
|
|
471 <help>
|
|
472
|
|
473 **What it Does**
|
|
474
|
|
475 Reverse the columns in a tabular file
|
|
476
|
|
477 </help>
|
|
478 <configfiles>
|
|
479 <configfile name="runMe">
|
|
480
|
|
481 # reverse order of columns in a tabular file
|
|
482 import sys
|
|
483 inp = sys.argv[1]
|
|
484 outp = sys.argv[2]
|
|
485 i = open(inp,'r')
|
|
486 o = open(outp,'w')
|
|
487 for row in i:
|
|
488 rs = row.rstrip().split('\t')
|
|
489 rs.reverse()
|
|
490 o.write('\t'.join(rs))
|
|
491 o.write('\n')
|
|
492 i.close()
|
|
493 o.close()
|
|
494
|
|
495
|
|
496 </configfile>
|
|
497 </configfiles>
|
|
498 </tool>
|
|
499
|
|
500 """
|
|
501
|
|
502 # these templates need a dict with the right keys to match the parameters - outputs, help, code...
|
|
503
|
|
504 xdict = {}
|
|
505 xdict['additionalParams'] = ''
|
|
506 xdict['additionalInputs'] = ''
|
|
507 if self.opts.additional_parameters:
|
|
508 if self.opts.edit_additional_parameters: # add to new tool form with default value set to original value
|
|
509 xdict['additionalInputs'] = '\n'.join(['<param name="%s" value="%s" label="%s" help="%s" type="%s"/>' % \
|
|
510 (x.split(',')[0],html_escape(x.split(',')[1]),html_escape(x.split(',')[2]),html_escape(x.split(',')[3]), x.split(',')[4]) for x in self.opts.additional_parameters])
|
|
511 xdict['additionalParams'] = '\n'.join(['<param name="%s" value="%s" />' % (x.split(',')[0],html_escape(x.split(',')[1])) for x in self.opts.additional_parameters])
|
|
512 xdict['interpreter_owner'] = self.interpreter_owner
|
|
513 xdict['interpreter_version'] = self.interpreter_version
|
|
514 xdict['interpreter_pack'] = self.interpreter_pack
|
|
515 xdict['interpreter_name'] = self.interpreter_name
|
|
516 xdict['requirements'] = ''
|
|
517 if self.opts.include_dependencies == "yes":
|
|
518 if self.opts.envshpath <> 'system':
|
|
519 xdict['requirements'] = self.protorequirements_interpreter % xdict
|
|
520 else:
|
|
521 xdict['requirements'] = self.protorequirements
|
|
522 xdict['tool_version'] = self.opts.tool_version
|
|
523 xdict['test1HTML'] = self.test1HTML
|
|
524 xdict['test1Output'] = self.test1Output
|
|
525 xdict['test1Inputs'] = self.test1Inputs
|
|
526 if self.opts.make_HTML and self.opts.output_tab:
|
|
527 xdict['tooltests'] = self.tooltestsBoth % xdict
|
|
528 elif self.opts.make_HTML:
|
|
529 xdict['tooltests'] = self.tooltestsHTMLOnly % xdict
|
|
530 else:
|
|
531 xdict['tooltests'] = self.tooltestsTabOnly % xdict
|
|
532 xdict['script'] = self.escapedScript
|
|
533 # configfile is least painful way to embed script to avoid external dependencies
|
|
534 # but requires escaping of <, > and $ to avoid Mako parsing
|
|
535 if self.opts.help_text:
|
|
536 helptext = open(self.opts.help_text,'r').readlines()
|
|
537 helptext = [html_escape(x) for x in helptext] # must html escape here too - thanks to Marius van den Beek
|
|
538 xdict['help'] = ''.join([x for x in helptext])
|
|
539 else:
|
|
540 xdict['help'] = 'Please ask the tool author (%s) for help as none was supplied at tool generation\n' % (self.opts.user_email)
|
|
541 coda = ['**Script**','Pressing execute will run the following code over your input file and generate some outputs in your history::']
|
|
542 coda.append('\n')
|
|
543 coda.append(self.indentedScript)
|
|
544 coda.append('\n**Attribution**\nThis Galaxy tool was created by %s at %s\nusing the Galaxy Tool Factory.\n' % (self.opts.user_email,timenow()))
|
|
545 coda.append('See %s for details of that project' % (toolFactoryURL))
|
|
546 coda.append('Please cite: Creating re-usable tools from scripts: The Galaxy Tool Factory. Ross Lazarus; Antony Kaspi; Mark Ziemann; The Galaxy Team. ')
|
|
547 coda.append('Bioinformatics 2012; doi: 10.1093/bioinformatics/bts573\n')
|
|
548 xdict['help'] = '%s\n%s' % (xdict['help'],'\n'.join(coda))
|
|
549 if self.opts.tool_desc:
|
|
550 xdict['tooldesc'] = '<description>%s</description>' % self.opts.tool_desc
|
|
551 else:
|
|
552 xdict['tooldesc'] = ''
|
|
553 xdict['command_outputs'] = ''
|
|
554 xdict['outputs'] = ''
|
|
555 if self.opts.input_tab:
|
|
556 cins = ['\n',]
|
|
557 cins.append('--input_formats %s' % self.opts.input_formats)
|
|
558 cins.append('#for intab in $input1:')
|
|
559 cins.append('--input_tab "${intab},${intab.name}"')
|
|
560 cins.append('#end for\n')
|
|
561 xdict['command_inputs'] = '\n'.join(cins)
|
|
562 xdict['inputs'] = '''<param name="input_tab" multiple="true" type="data" format="%s" label="Select one or more %s input files from your history"
|
|
563 help="Multiple inputs may be selected assuming the script can deal with them..."/> \n''' % (self.inputFormats,self.inputFormats)
|
|
564 else:
|
|
565 xdict['command_inputs'] = '' # assume no input - eg a random data generator
|
|
566 xdict['inputs'] = ''
|
|
567 if (len(self.opts.additional_parameters) > 0):
|
|
568 cins = ['\n',]
|
|
569 for params in self.opts.additional_parameters:
|
|
570 psplit = params.split(',') # name,value...
|
|
571 psplit[3] = html_escape(psplit[3])
|
|
572 if self.opts.edit_additional_parameters:
|
|
573 psplit[1] = '$%s' % psplit[0] # replace with form value
|
|
574 else:
|
|
575 psplit[1] = html_escape(psplit[1]) # leave prespecified value
|
|
576 cins.append('--additional_parameters """%s"""' % ','.join(psplit))
|
|
577 xdict['command_inputs'] = '%s\n%s' % (xdict['command_inputs'],'\n'.join(cins))
|
|
578 xdict['inputs'] += '<param name="job_name" type="text" size="60" label="Supply a name for the outputs to remind you what they contain" value="%s"/> \n' % self.toolname
|
|
579 xdict['toolname'] = self.toolname
|
|
580 xdict['toolid'] = self.toolid
|
|
581 xdict['interpreter'] = self.opts.interpreter
|
|
582 xdict['scriptname'] = self.sfile
|
|
583 if self.opts.make_HTML:
|
|
584 xdict['command_outputs'] += ' --output_dir "$html_file.files_path" --output_html "$html_file" --make_HTML "yes"'
|
|
585 xdict['outputs'] += ' <data format="html" name="html_file" label="${job_name}.html"/>\n'
|
|
586 else:
|
|
587 xdict['command_outputs'] += ' --output_dir "./"'
|
|
588 if self.opts.output_tab:
|
|
589 xdict['command_outputs'] += ' --output_tab "$output1"'
|
|
590 xdict['outputs'] += ' <data format="%s" name="output1" label="${job_name}"/>\n' % self.outFormats
|
|
591 xdict['command'] = self.newCommand % xdict
|
|
592 if self.opts.citations:
|
|
593 citationstext = open(self.opts.citations,'r').read()
|
|
594 citation_tuples = parse_citations(citationstext)
|
|
595 citations_xml = ""
|
|
596 for citation_type, citation_content in citation_tuples:
|
|
597 citation_xml = """<citation type="%s">%s</citation>""" % (citation_type, html_escape(citation_content))
|
|
598 citations_xml += citation_xml
|
|
599 xdict['citations'] = citations_xml
|
|
600 else:
|
|
601 xdict['citations'] = ""
|
|
602 xmls = self.newXML % xdict
|
|
603 xf = open(self.xmlfile,'w')
|
|
604 xf.write(xmls)
|
|
605 xf.write('\n')
|
|
606 xf.close()
|
|
607 # ready for the tarball
|
|
608
|
|
609
|
|
610 def makeTooltar(self):
|
|
611 """
|
|
612 a tool is a gz tarball with eg
|
|
613 /toolname/tool.xml /toolname/tool.py /toolname/test-data/test1_in.foo ...
|
|
614 """
|
|
615 retval = self.run()
|
|
616 if retval:
|
|
617 print >> sys.stderr,'## Run failed. Cannot build yet. Please fix and retry'
|
|
618 sys.exit(1)
|
|
619 tdir = self.toolname
|
|
620 os.mkdir(tdir)
|
|
621 self.makeXML()
|
|
622 if self.opts.help_text:
|
|
623 hlp = open(self.opts.help_text,'r').read()
|
|
624 else:
|
|
625 hlp = 'Please ask the tool author for help as none was supplied at tool generation\n'
|
|
626 readme_dict = {'readme':hlp,'interpreter':self.opts.interpreter,'interpreter_version':self.interpreter_version,'interpreter_name':self.interpreter_name,
|
14
|
627 'interpreter_owner':self.interpreter_owner,'interpreter_pack':self.interpreter_pack}
|
13
|
628 if self.opts.include_dependencies == "yes":
|
|
629 if self.opts.envshpath == 'system':
|
|
630 tooldepcontent = self.toolhtmldepskel % readme_dict
|
|
631 else:
|
|
632 tooldepcontent = self.toolhtmldepinterpskel % readme_dict
|
|
633 else:
|
|
634 tooldepcontent = self.emptytoolhtmldepskel % readme_dictls -l
|
|
635 depf = open(os.path.join(tdir,'tool_dependencies.xml'),'w')
|
|
636 depf.write(tooldepcontent)
|
|
637 depf.write('\n')
|
|
638 depf.close()
|
14
|
639 testdir = os.path.join(tdir,'test-data')
|
|
640 os.mkdir(testdir) # make tests directory
|
|
641 for i,intab in enumerate(self.opts.input_tab):
|
|
642 si = self.opts.input_tab[i]
|
|
643 if si.find(',') <> -1:
|
|
644 s = si.split(',')[0]
|
|
645 si = s
|
|
646 dest = os.path.join(testdir,os.path.basename(si))
|
|
647 if si <> dest:
|
|
648 shutil.copyfile(si,dest)
|
|
649 if self.opts.output_tab:
|
|
650 shutil.copyfile(self.opts.output_tab,os.path.join(testdir,self.test1Output))
|
|
651 if self.opts.make_HTML:
|
|
652 shutil.copyfile(self.opts.output_html,os.path.join(testdir,self.test1HTML))
|
|
653 if self.opts.output_dir:
|
|
654 shutil.copyfile(self.tlog,os.path.join(testdir,'test1_out.log'))
|
13
|
655 outpif = '%s.py' % self.toolname # new name
|
|
656 outpiname = os.path.join(tdir,outpif) # path for the tool tarball
|
|
657 pyin = os.path.basename(self.pyfile) # our name - we rewrite ourselves (TM)
|
|
658 notes = ['# %s - a self annotated version of %s generated by running %s\n' % (outpiname,pyin,pyin),]
|
|
659 notes.append('# to make a new Galaxy tool called %s\n' % self.toolname)
|
|
660 notes.append('# User %s at %s\n' % (self.opts.user_email,timenow()))
|
|
661 pi = open(self.pyfile,'r').readlines() # our code becomes new tool wrapper (!) - first Galaxy worm
|
|
662 notes += pi
|
|
663 outpi = open(outpiname,'w')
|
|
664 outpi.write(''.join(notes))
|
|
665 outpi.write('\n')
|
|
666 outpi.close()
|
|
667 stname = os.path.join(tdir,self.sfile)
|
|
668 if not os.path.exists(stname):
|
|
669 shutil.copyfile(self.sfile, stname)
|
|
670 xtname = os.path.join(tdir,self.xmlfile)
|
|
671 if not os.path.exists(xtname):
|
|
672 shutil.copyfile(self.xmlfile,xtname)
|
|
673 tarpath = "%s.tar.gz" % self.toolname
|
|
674 tar = tarfile.open(tarpath, "w:gz")
|
|
675 tar.add(tdir,arcname='%s' % self.toolname)
|
|
676 tar.close()
|
|
677 shutil.copyfile(tarpath,self.opts.new_tool)
|
|
678 shutil.rmtree(tdir)
|
|
679 ## TODO: replace with optional direct upload to local toolshed?
|
|
680 return retval
|
|
681
|
|
682
|
|
683 def compressPDF(self,inpdf=None,thumbformat='png'):
|
|
684 """need absolute path to pdf
|
|
685 note that GS gets confoozled if no $TMP or $TEMP
|
|
686 so we set it
|
|
687 """
|
|
688 assert os.path.isfile(inpdf), "## Input %s supplied to %s compressPDF not found" % (inpdf,self.myName)
|
|
689 hlog = os.path.join(self.opts.output_dir,"compress_%s.txt" % os.path.basename(inpdf))
|
|
690 sto = open(hlog,'a')
|
|
691 our_env = os.environ.copy()
|
|
692 our_tmp = our_env.get('TMP',None)
|
|
693 if not our_tmp:
|
|
694 our_tmp = our_env.get('TEMP',None)
|
|
695 if not (our_tmp and os.path.exists(our_tmp)):
|
|
696 newtmp = os.path.join(self.opts.output_dir,'tmp')
|
|
697 try:
|
|
698 os.mkdir(newtmp)
|
|
699 except:
|
|
700 sto.write('## WARNING - cannot make %s - it may exist or permissions need fixing\n' % newtmp)
|
|
701 our_env['TEMP'] = newtmp
|
|
702 if not self.temp_warned:
|
|
703 sto.write('## WARNING - no $TMP or $TEMP!!! Please fix - using %s temporarily\n' % newtmp)
|
|
704 self.temp_warned = True
|
|
705 outpdf = '%s_compressed' % inpdf
|
|
706 cl = ["gs", "-sDEVICE=pdfwrite", "-dNOPAUSE", "-dUseCIEColor", "-dBATCH","-dPDFSETTINGS=/printer", "-sOutputFile=%s" % outpdf,inpdf]
|
|
707 x = subprocess.Popen(cl,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
|
|
708 retval1 = x.wait()
|
|
709 sto.close()
|
|
710 if retval1 == 0:
|
|
711 os.unlink(inpdf)
|
|
712 shutil.move(outpdf,inpdf)
|
|
713 os.unlink(hlog)
|
|
714 hlog = os.path.join(self.opts.output_dir,"thumbnail_%s.txt" % os.path.basename(inpdf))
|
|
715 sto = open(hlog,'w')
|
|
716 outpng = '%s.%s' % (os.path.splitext(inpdf)[0],thumbformat)
|
|
717 if self.useGM:
|
|
718 cl2 = ['gm', 'convert', inpdf, outpng]
|
|
719 else: # assume imagemagick
|
|
720 cl2 = ['convert', inpdf, outpng]
|
|
721 x = subprocess.Popen(cl2,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
|
|
722 retval2 = x.wait()
|
|
723 sto.close()
|
|
724 if retval2 == 0:
|
|
725 os.unlink(hlog)
|
|
726 retval = retval1 or retval2
|
|
727 return retval
|
|
728
|
|
729
|
|
730 def getfSize(self,fpath,outpath):
|
|
731 """
|
|
732 format a nice file size string
|
|
733 """
|
|
734 size = ''
|
|
735 fp = os.path.join(outpath,fpath)
|
|
736 if os.path.isfile(fp):
|
|
737 size = '0 B'
|
|
738 n = float(os.path.getsize(fp))
|
|
739 if n > 2**20:
|
|
740 size = '%1.1f MB' % (n/2**20)
|
|
741 elif n > 2**10:
|
|
742 size = '%1.1f KB' % (n/2**10)
|
|
743 elif n > 0:
|
|
744 size = '%d B' % (int(n))
|
|
745 return size
|
|
746
|
|
747 def makeHtml(self):
|
|
748 """ Create an HTML file content to list all the artifacts found in the output_dir
|
|
749 """
|
|
750
|
|
751 galhtmlprefix = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
752 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
|
753 <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
754 <meta name="generator" content="Galaxy %s tool output - see http://g2.trac.bx.psu.edu/" />
|
|
755 <title></title>
|
|
756 <link rel="stylesheet" href="/static/style/base.css" type="text/css" />
|
|
757 </head>
|
|
758 <body>
|
|
759 <div class="toolFormBody">
|
|
760 """
|
|
761 galhtmlattr = """<hr/><div class="infomessage">This tool (%s) was generated by the <a href="https://bitbucket.org/fubar/galaxytoolfactory/overview">Galaxy Tool Factory</a></div><br/>"""
|
|
762 galhtmlpostfix = """</div></body></html>\n"""
|
|
763
|
|
764 flist = os.listdir(self.opts.output_dir)
|
|
765 flist = [x for x in flist if x <> 'Rplots.pdf']
|
|
766 flist.sort()
|
|
767 html = []
|
|
768 html.append(galhtmlprefix % progname)
|
|
769 html.append('<div class="infomessage">Galaxy Tool "%s" run at %s</div><br/>' % (self.toolname,timenow()))
|
|
770 fhtml = []
|
|
771 if len(flist) > 0:
|
|
772 logfiles = [x for x in flist if x.lower().endswith('.log')] # log file names determine sections
|
|
773 logfiles.sort()
|
|
774 logfiles = [x for x in logfiles if os.path.abspath(x) <> os.path.abspath(self.tlog)]
|
|
775 logfiles.append(os.path.abspath(self.tlog)) # make it the last one
|
|
776 pdflist = []
|
|
777 npdf = len([x for x in flist if os.path.splitext(x)[-1].lower() == '.pdf'])
|
|
778 for rownum,fname in enumerate(flist):
|
|
779 dname,e = os.path.splitext(fname)
|
|
780 sfsize = self.getfSize(fname,self.opts.output_dir)
|
|
781 if e.lower() == '.pdf' : # compress and make a thumbnail
|
|
782 thumb = '%s.%s' % (dname,self.thumbformat)
|
|
783 pdff = os.path.join(self.opts.output_dir,fname)
|
|
784 retval = self.compressPDF(inpdf=pdff,thumbformat=self.thumbformat)
|
|
785 if retval == 0:
|
|
786 pdflist.append((fname,thumb))
|
|
787 else:
|
|
788 pdflist.append((fname,fname))
|
|
789 if (rownum+1) % 2 == 0:
|
|
790 fhtml.append('<tr class="odd_row"><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname,fname,sfsize))
|
|
791 else:
|
|
792 fhtml.append('<tr><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname,fname,sfsize))
|
|
793 for logfname in logfiles: # expect at least tlog - if more
|
|
794 if os.path.abspath(logfname) == os.path.abspath(self.tlog): # handled later
|
|
795 sectionname = 'All tool run'
|
|
796 if (len(logfiles) > 1):
|
|
797 sectionname = 'Other'
|
|
798 ourpdfs = pdflist
|
|
799 else:
|
|
800 realname = os.path.basename(logfname)
|
|
801 sectionname = os.path.splitext(realname)[0].split('_')[0] # break in case _ added to log
|
|
802 ourpdfs = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] == sectionname]
|
|
803 pdflist = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] <> sectionname] # remove
|
|
804 nacross = 1
|
|
805 npdf = len(ourpdfs)
|
|
806
|
|
807 if npdf > 0:
|
|
808 nacross = math.sqrt(npdf) ## int(round(math.log(npdf,2)))
|
|
809 if int(nacross)**2 != npdf:
|
|
810 nacross += 1
|
|
811 nacross = int(nacross)
|
|
812 width = min(400,int(1200/nacross))
|
|
813 html.append('<div class="toolFormTitle">%s images and outputs</div>' % sectionname)
|
|
814 html.append('(Click on a thumbnail image to download the corresponding original PDF image)<br/>')
|
|
815 ntogo = nacross # counter for table row padding with empty cells
|
|
816 html.append('<div><table class="simple" cellpadding="2" cellspacing="2">\n<tr>')
|
|
817 for i,paths in enumerate(ourpdfs):
|
|
818 fname,thumb = paths
|
|
819 s= """<td><a href="%s"><img src="%s" title="Click to download a PDF of %s" hspace="5" width="%d"
|
|
820 alt="Image called %s"/></a></td>\n""" % (fname,thumb,fname,width,fname)
|
|
821 if ((i+1) % nacross == 0):
|
|
822 s += '</tr>\n'
|
|
823 ntogo = 0
|
|
824 if i < (npdf - 1): # more to come
|
|
825 s += '<tr>'
|
|
826 ntogo = nacross
|
|
827 else:
|
|
828 ntogo -= 1
|
|
829 html.append(s)
|
|
830 if html[-1].strip().endswith('</tr>'):
|
|
831 html.append('</table></div>\n')
|
|
832 else:
|
|
833 if ntogo > 0: # pad
|
|
834 html.append('<td> </td>'*ntogo)
|
|
835 html.append('</tr></table></div>\n')
|
|
836 logt = open(logfname,'r').readlines()
|
|
837 logtext = [x for x in logt if x.strip() > '']
|
|
838 html.append('<div class="toolFormTitle">%s log output</div>' % sectionname)
|
|
839 if len(logtext) > 1:
|
|
840 html.append('\n<pre>\n')
|
|
841 html += logtext
|
|
842 html.append('\n</pre>\n')
|
|
843 else:
|
|
844 html.append('%s is empty<br/>' % logfname)
|
|
845 if len(fhtml) > 0:
|
|
846 fhtml.insert(0,'<div><table class="colored" cellpadding="3" cellspacing="3"><tr><th>Output File Name (click to view)</th><th>Size</th></tr>\n')
|
|
847 fhtml.append('</table></div><br/>')
|
|
848 html.append('<div class="toolFormTitle">All output files available for downloading</div>\n')
|
|
849 html += fhtml # add all non-pdf files to the end of the display
|
|
850 else:
|
|
851 html.append('<div class="warningmessagelarge">### Error - %s returned no files - please confirm that parameters are sane</div>' % self.opts.interpreter)
|
|
852 html.append(galhtmlpostfix)
|
|
853 htmlf = file(self.opts.output_html,'w')
|
|
854 htmlf.write('\n'.join(html))
|
|
855 htmlf.write('\n')
|
|
856 htmlf.close()
|
|
857 self.html = html
|
|
858
|
|
859
|
|
860
|
|
861 def run(self):
|
|
862 """
|
|
863 scripts must be small enough not to fill the pipe!
|
|
864 """
|
|
865 if self.opts.envshpath <> 'system':
|
|
866 shell_source(self.opts.envshpath)
|
|
867 if self.treatbashSpecial and self.opts.interpreter in ['bash','sh']:
|
|
868 retval = self.runBash()
|
|
869 else:
|
|
870 if self.opts.output_dir:
|
|
871 ste = open(self.elog,'w')
|
|
872 sto = open(self.tlog,'w')
|
|
873 sto.write('## Toolfactory generated command line = %s\n' % ' '.join(self.cl))
|
|
874 sto.flush()
|
|
875 p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=ste,cwd=self.opts.output_dir)
|
|
876 else:
|
|
877 p = subprocess.Popen(self.cl,shell=False)
|
|
878 retval = p.wait()
|
|
879 if self.opts.output_dir:
|
|
880 sto.close()
|
|
881 ste.close()
|
|
882 err = open(self.elog,'r').readlines()
|
|
883 if retval <> 0 and err: # problem
|
|
884 print >> sys.stderr,err
|
|
885 if self.opts.make_HTML:
|
|
886 self.makeHtml()
|
|
887 return retval
|
|
888
|
|
889 def runBash(self):
|
|
890 """
|
|
891 cannot use - for bash so use self.sfile
|
|
892 """
|
|
893 if self.opts.output_dir:
|
|
894 s = '## Toolfactory generated command line = %s\n' % ' '.join(self.cl)
|
|
895 sto = open(self.tlog,'w')
|
|
896 sto.write(s)
|
|
897 sto.flush()
|
|
898 p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=sto,cwd=self.opts.output_dir)
|
|
899 else:
|
|
900 p = subprocess.Popen(self.cl,shell=False)
|
|
901 retval = p.wait()
|
|
902 if self.opts.output_dir:
|
|
903 sto.close()
|
|
904 if self.opts.make_HTML:
|
|
905 self.makeHtml()
|
|
906 return retval
|
|
907
|
|
908
|
|
909 def main():
|
|
910 u = """
|
|
911 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
|
|
912 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath" --tool_name "foo" --interpreter "Rscript"
|
|
913 </command>
|
|
914 """
|
|
915 op = optparse.OptionParser()
|
|
916 a = op.add_option
|
|
917 a('--script_path',default=None)
|
|
918 a('--tool_name',default=None)
|
|
919 a('--interpreter',default=None)
|
|
920 a('--output_dir',default='./')
|
|
921 a('--output_html',default=None)
|
|
922 a('--input_tab',default=[], action="append") # these are "galaxypath,metadataname" pairs
|
|
923 a("--input_formats",default="tabular")
|
|
924 a('--output_tab',default=None)
|
|
925 a('--output_format',default='tabular')
|
|
926 a('--user_email',default='Unknown')
|
|
927 a('--bad_user',default=None)
|
|
928 a('--make_Tool',default=None)
|
|
929 a('--make_HTML',default=None)
|
|
930 a('--help_text',default=None)
|
|
931 a('--tool_desc',default=None)
|
|
932 a('--new_tool',default=None)
|
|
933 a('--tool_version',default=None)
|
|
934 a('--include_dependencies',default="yes")
|
|
935 a('--citations',default=None)
|
|
936 a('--additional_parameters', dest='additional_parameters', action='append', default=[])
|
|
937 a('--edit_additional_parameters', action="store_true", default=False)
|
|
938 a('--envshpath',default="system")
|
|
939 opts, args = op.parse_args()
|
|
940 assert not opts.bad_user,'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to admin_users in universe_wsgi.ini' % (opts.bad_user,opts.bad_user)
|
|
941 assert opts.tool_name,'## Tool Factory expects a tool name - eg --tool_name=DESeq'
|
|
942 assert opts.interpreter,'## Tool Factory wrapper expects an interpreter - eg --interpreter=Rscript'
|
|
943 assert os.path.isfile(opts.script_path),'## Tool Factory wrapper expects a script path - eg --script_path=foo.R'
|
|
944 if opts.output_dir:
|
|
945 try:
|
|
946 os.makedirs(opts.output_dir)
|
|
947 except:
|
|
948 pass
|
|
949 opts.input_tab = [x.replace('"','').replace("'",'') for x in opts.input_tab]
|
|
950 for i,x in enumerate(opts.additional_parameters): # remove quotes we need to deal with spaces in CL params
|
|
951 opts.additional_parameters[i] = opts.additional_parameters[i].replace('"','')
|
|
952 r = ScriptRunner(opts)
|
|
953 if opts.make_Tool:
|
|
954 retcode = r.makeTooltar()
|
|
955 else:
|
|
956 retcode = r.run()
|
|
957 os.unlink(r.sfile)
|
|
958 if retcode:
|
|
959 sys.exit(retcode) # indicate failure to job runner
|
|
960
|
|
961
|
|
962 if __name__ == "__main__":
|
|
963 main()
|
|
964
|
|
965
|