forked from emanuelez/PySynergy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSynergySession.py
288 lines (228 loc) · 9.1 KB
/
SynergySession.py
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python
# encoding: utf-8
"""
untitled.py
Created by Emanuele Zattin on 2010-11-08.
Copyright (c) 2010 Emanuele Zattin. All rights reserved.
"""
import os
from subprocess import Popen, PIPE
class SynergySession:
"""This class is a wrapper around the Synergy command line client"""
def __init__(self, database, engine = None, command_name = 'ccm', ccm_ui_path = '/dev/null', ccm_eng_path = '/dev/null'):
self.command_name = command_name
self.database = database
self.engine = engine
self.num_of_cmds = 0
# This dictionary will contain the status of the next command and will be emptied by self.run()
self.command = ''
self.status = {}
# Store the warnings and errors that might be found along the preparation or execution of a command
self.warnings = []
self.errors = []
# Open the session
args = [self.command_name]
args.append('start')
args.append('-nogui')
args.append('-d')
args.append(self.database) # database
args.append('-m') # permit multiple sessions
args.append('-q') #quiet
if self.engine:
args.append('-d')
args.append(self.engine) # engine
self.environment = os.environ
self.environment['CCM_UILOG'] = ccm_ui_path
self.environment['CCM_ENGLOG'] = ccm_eng_path
# Open the session
p = Popen(args, stdout=PIPE, stderr=PIPE, env=self.environment)
self.num_of_cmds += 1
# Store the session data
#p.wait()
stdout, stderr = p.communicate()
if stderr:
raise SynergyException('Error while starting a synergy Session: ' + stderr)
# Set the environment variable for the Synergy session
self.environment['CCM_ADDR'] = stdout
# Get the delimiter and store it
self.delimiter = self.delim()
def __del__(self):
# Close the session
self.stop()
print "Number of commands issued:", str(self.num_of_cmds)
def _reset_status(self):
"""Reset the status of the object"""
self.command = ''
self.status = {}
self.warnings = []
self.errors = []
def _run(self, command):
"""Execute a Synergy command"""
if not command[0] == self.command_name:
command.insert(0, self.command_name)
p = Popen(command, stdout=PIPE, stderr=PIPE, env=self.environment)
self.num_of_cmds += 1
# Store the result as a single string. It will be splitted later
#p.wait()
stdout, stderr = p.communicate()
if stderr:
raise SynergyException('Error while running the Synergy command: %s \nError message: %s' % (command, stderr))
return stdout
def delim(self):
"""Returns the delimiter defined in the Synergy DB"""
self._reset_status()
return self._run(['delim']).strip()
def stop(self):
"""Stops the current Synergy session"""
if 'CCM_ADDR' in self.environment:
self._run(['stop'])
def query(self, query_string):
"""Set a query that will be executed"""
self.command = 'query'
self.status['arguments'] = [query_string]
self.status['formattable'] = True
if 'format' not in self.status:
self.status['format'] = ['%objectname']
return self
def cat(self, object_name):
"""Cat an object"""
self.command = 'cat'
self.status['arguments'] = [object_name]
self.status['formattable'] = False
if 'format' in self.status:
self.status['format'] = []
return self
def finduse(self, object_name):
"""Finduse of an object"""
self.command = 'finduse'
self.status['arguments'] = [object_name]
self.status['option'] = []
self.status['formattable'] = False
if 'format' in self.status:
self.status['format'] = []
return self
def attr(self, object_name):
"""Attributes of an object"""
self.command = 'attr'
self.status['arguments'] = [object_name]
self.status['option'] = []
self.status['formattable'] = False
if 'format' in self.status:
self.status['format'] = []
return self
def task(self, task, formattable = False):
"""Task command"""
self.command = 'task'
self.status['arguments'] = [task]
self.status['option'] = []
self.status['formattable'] = formattable
if 'format' not in self.status:
self.status['format'] = ['%objectname']
return self
def rp(self, project):
"""Reconfigure properties command"""
self.command = 'rp'
self.status['arguments'] = [project]
self.status['option'] = []
self.status['formattable'] = True
if 'format' not in self.status:
self.status['format'] = ['%objectname']
return self
def diff(self, new, old):
"""Difference between to files"""
self.command = 'diff'
self.status['arguments'] = [old, new]
self.status['option'] = []
self.status['formattable'] = False
if 'format' in self.status:
self.status['format'] = []
return self
def format(self, format):
"""Sets the output format for the command, if it supports formatting.
The input can be an iterable or a string"""
if isinstance(format, str):
if 'format' not in self.status:
self.status['format'] = []
self.status['format'].append(format)
return self
if not hasattr(format, '__iter__'):
self.warnings.append('The argument of format(format) must be something iterable or a string')
return self
if not self.status['format']:
for element in format:
self.status['format'].append(element)
return self
def option(self, option):
"""Sets the options for the command, if it supports options.
The input can be an iterable or a string"""
if isinstance(option, str):
if 'option' not in self.status:
self.status['option'] = []
self.status['option'].append(option)
return self
if not hasattr(option, '__iter__'):
self.warnings.append('The argument of option(option) must be something iterable or a string')
return self
if not self.status['option']:
for element in option:
self.status['option'].append(element)
return self
def run(self):
"""
Run the Synergy command.
At this point the command must be already set by i.e. query()
"""
if not self.status:
self.errors.append('before run() the status of the command must be already set')
command = [self.command_name]
command.append(self.command)
if 'formattable' in self.status and self.status['formattable']:
if 'format' not in self.status:
raise SynergyException("status['format'] undefined")
command.append('-u')
if 'task' not in command and 'rp' not in command:
command.append('-nf')
command.append('-f')
command.append('|SEPARATOR|'.join(self.status['format']) + '|ITEM_SEPARATOR|')
if 'arguments' not in self.status:
raise SynergyException("status['arguments'] undefined")
if 'option' in self.status:
for element in self.status['option']:
command.append(element)
command.extend(self.status['arguments'])
result = self._run(command)
# Parse the result and return it
if 'formattable' in self.status and self.status['formattable']:
if not result:
# Clean up
self._reset_status()
return []
final_result = []
for item in result.split('|ITEM_SEPARATOR|')[:-1]:
splitted_item = item.split('|SEPARATOR|')
if len(splitted_item) != len(self.status['format']):
raise SynergyException("the length of status['format'] and the splitted result is not the same")
line = {}
for k, v in zip(self.status['format'], splitted_item):
line[k[1:]] = v.strip()
final_result.append(line)
# Clean up
self._reset_status()
return final_result
else:
# Clean up
self._reset_status()
return result
class SynergyException(Exception):
"""User defined exception raised by SynergySession"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def main():
# Test
ccm = SynergySession('/nokia/co_nmp/groups/gscm/dbs/co1asset')
results = ccm.query("is_associated_cv_of(task('co1asset#113266'))").format("%objectname").run()
print results
if __name__ == '__main__':
main()