-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpowersnake.py
More file actions
189 lines (145 loc) · 5.66 KB
/
Copy pathpowersnake.py
File metadata and controls
189 lines (145 loc) · 5.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python3
#
# powersnake.py
# - A set of common utility functions which are very useful in most Snakefiles.
#
# Copyright (c) 2015 Hyeshik Chang
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
__all__ = ['init_powersnake', 'external_script', 'init_powersnake',
'load_snakemake_params', 'is_snakemake_child', 'suffix_filter',
'tmpfile', 'notify']
from snakemake.shell import shell
import os
import tempfile
PARAMETER_PASSING_ENVVAR = 'SNAKEMAKE_PARAMS'
PUSHBULLET_ENVVAR = 'SNAKEMAKE_PUSHBULLET_APIKEY'
def is_snakemake_running():
import inspect
for outerframe in inspect.getouterframes(inspect.currentframe()):
if outerframe[1].endswith('snakemake/__init__.py'):
return True
else:
return False
is_snakemake_child = lambda: False
def init_powersnake():
# pipefail is supported by bash only.
shell.executable(os.popen('which bash').read().strip())
shell.prefix('set -e; set -o pipefail; ')
def load_snakemake_params():
global is_snakemake_child
if PARAMETER_PASSING_ENVVAR not in os.environ:
return
is_snakemake_child = lambda: True
import json, collections
from snakemake.io import Namedlist
import builtins
options = json.load(open(os.environ[PARAMETER_PASSING_ENVVAR]))
# Unset the parameter file var not to pass to children.
del os.environ[PARAMETER_PASSING_ENVVAR]
for varname, value in options.items():
if not isinstance(value, int):
nl = Namedlist()
for k, v in value:
nl.append(v)
if k is not None:
nl._add_name(k)
value = nl
setattr(builtins, varname, value)
def external_script(_command):
import inspect, json, tempfile
VARS_TO_PASS = 'input output threads wildcards params'.split()
callerlocal = inspect.currentframe().f_back.f_locals
callerglobal = inspect.currentframe().f_back.f_globals
packed = {}
for var in VARS_TO_PASS:
if isinstance(callerlocal[var], int):
packed[var] = callerlocal[var]
else:
packed[var] = list(callerlocal[var]._allitems())
with tempfile.NamedTemporaryFile(mode='wt') as tmpfile:
json.dump(packed, tmpfile)
tmpfile.flush()
os.environ[PARAMETER_PASSING_ENVVAR] = tmpfile.name
try:
locals().update(callerglobal)
locals().update(callerlocal)
shell(_command)
finally:
del os.environ[PARAMETER_PASSING_ENVVAR]
class suffix_filter:
def __init__(self, values):
self.values = values
def __getitem__(self, key):
matches = [el for el in self.values if el.endswith(key)]
if len(matches) > 1:
raise ValueError("No single match found for {} in {}".format(key, self.values))
elif len(matches) == 1:
return matches[0]
else:
return ''
class temporary_file(str):
def __new__(cls, suffix='', prefix='tmp', dir=None):
tmpfile = tempfile.NamedTemporaryFile(suffix=suffix, prefix=prefix, dir=dir)
self = str.__new__(cls, tmpfile.name)
self.tmpfile = tmpfile
return self
def __del__(self):
self.tmpfile.close()
try:
os.unlink(self.tmpfile.name)
except:
pass
def tmpfile(*args, **kwds):
def finalize_temporary_file(_):
return temporary_file(*args, **kwds)
return finalize_temporary_file
try:
import pushbullet
PUSHBULLET_ENVVAR = 'SNAKEMAKE_PUSHBULLET_APIKEY'
if PUSHBULLET_ENVVAR not in os.environ:
raise ValueError("PushBullet API key is not defined in {}.".format(PUSHBULLET_ENVVAR))
class PushBulletNotifier:
def __init__(self, apikey, log_tail_length=30):
self.apikey = apikey
self.log_tail_length = log_tail_length
self.pb = None
def check_connection(self):
if self.pb is None:
self.pb = pushbullet.PushBullet(self.apikey)
def message(self, title, msg, logfile=None):
self.check_connection()
self.pb.push_note(title, msg)
if logfile is not None:
logtail = open(logfile).readlines()[-self.log_tail_length:]
self.pb.push_file(''.join(logtail), 'log.txt', file_type='text/plain')
notify = PushBulletNotifier(os.environ[PUSHBULLET_ENVVAR])
except (ImportError, ValueError):
class DummyNotifier:
def __init__(self):
pass
def message(self, title, msg, logfile=None):
pass
notify = DummyNotifier()
# Call initializing functions
if is_snakemake_running():
init_powersnake()
else:
load_snakemake_params()