-
Notifications
You must be signed in to change notification settings - Fork 2
/
rtc.py
executable file
·614 lines (553 loc) · 29.1 KB
/
rtc.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#!/usr/bin/env python
# frediz@linux.vnet.ibm.com
import requests
import warnings
import json
import pprint
import re
import os, sys
import select
import html2text
import getpass
import argparse
import tempfile, subprocess
import ConfigParser
## color stuff
class cl:
"""
Colors class:
reset all colors with colors.reset
two subclasses fg for foreground and bg for background.
use as colors.subclass.colorname.
i.e. colors.fg.red or colors.bg.green
also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. colors.bold
"""
colorize = True
reset='\033[0m'
bold='\033[01m'
disable='\033[02m'
underline='\033[04m'
reverse='\033[07m'
strikethrough='\033[09m'
invisible='\033[08m'
# return colorized string
@classmethod
def str(cls, string, color):
if cl.colorize:
return color+string+cl.reset
return string
class fg:
black='\033[30m'
red='\033[31m'
green='\033[32m'
orange='\033[33m'
blue='\033[34m'
purple='\033[35m'
cyan='\033[36m'
lightgrey='\033[37m'
darkgrey='\033[90m'
lightred='\033[91m'
lightgreen='\033[92m'
yellow='\033[93m'
lightblue='\033[94m'
pink='\033[95m'
lightcyan='\033[96m'
class bg:
black='\033[40m'
red='\033[41m'
green='\033[42m'
orange='\033[43m'
blue='\033[44m'
purple='\033[45m'
cyan='\033[46m'
lightgrey='\033[47m'
## end of color
class RTCClient(object):
HOST = 'https://jazz06.rchland.ibm.com:12443/jazz/'
PROJECT = '_zNTKcB3lEeK8Y908RIgA1A'
def __init__(self, user, password):
self.user = user
self.password = password
self.session = requests.Session()
r = self.get_authed_session()
try:
json.loads(r.text)
except:
print "Authentication failed."
sys.exit(1)
self.category='_LqSO0L0qEeSLGNNvkdKuNQ'
def sget(self, url, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore", requests.packages.urllib3.exceptions.InsecureRequestWarning)
return self.session.get(RTCClient.HOST + url, allow_redirects=True, verify=False, **kwargs)
def spost(self, url, **kwargs):
return self.session.post(RTCClient.HOST + url, allow_redirects=True, verify=False, **kwargs)
def sput(self, url, **kwargs):
return self.session.put(RTCClient.HOST + url, allow_redirects=True, verify=False, **kwargs)
def spatch(self, url, **kwargs):
return self.session.patch(RTCClient.HOST + url, allow_redirects=True, verify=False, **kwargs)
def get_authed_session(self):
self.sget('authenticated/identity', headers={'Accept':'application/xml'})
return self.spost('j_security_check', data={'j_username':self.user,'j_password':self.password})
class Workitem(object):
def getStateColor(self):
#should be implemented else :
return cl.reverse
def stateColorize(self, string):
return cl.str(string, self.getStateColor())
@classmethod
def __createItem(c, client, json):
for cls in Workitem.__subclasses__():
if json['dc:type']['rdf:resource'] == cls.TYPE:
return cls(client, json['dc:identifier'], json)
raise ValueError
@classmethod
def getOne(cls, client, workitemid, json_query = ""):
r = client.sget('oslc/workitems/'+ str(workitemid) +'.json'+json_query)
if r.status_code == 200:
return Workitem.__createItem(client, json.loads(r.text))
elif r.status_code in [ 400, 404 ]:
js = json.loads(r.text)
print "Error while getting workitem id '%s' :" % workitemid
print js['oslc_cm:message']
else:
print "Unknown error : %s [%s]" % (r.reason, r.status_code)
print r.text
sys.exit(1)
@classmethod
def getList(cls, client, json_query = ""):
r = client.sget(json_query)
workitems = json.loads(r.text)['oslc_cm:results']
return map(lambda x: Workitem.__createItem(client, x), workitems)
@classmethod
def createOne(cls, client, title, description, witype, owner = None):
js = {
'dc:description': description,
'dc:title': title,
'dc:type': { 'rdf:resource': witype },
'rtc_cm:filedAgainst': { 'rdf:resource': RTCClient.HOST + 'resource/itemOid/com.ibm.team.workitem.Category/%s'%(client.category) },
}
if owner is not None:
js['rtc_cm:ownedBy'] = owner
r = client.spost('oslc/contexts/'+ RTCClient.PROJECT+'/workitems', json=js, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'});
return Workitem.__createItem(client, json.loads(r.text))
def __init__(self, jclient, workitemid = None, json = {}):
self.jclient = jclient
self.workitemid = workitemid
self.js = json
def get_comments(self):
r = self.jclient.sget('oslc/workitems/'+ str(self.workitemid) +'/rtc_cm:comments.json?oslc_cm.properties=dc:created,dc:description,dc:creator{dc:title}')
return json.loads(r.text)
def add_comment(self, comment):
return self.jclient.spost('oslc/workitems/'+ str(self.workitemid) +'/rtc_cm:comments', json={'dc:description':comment}, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
def change(self, js):
return self.jclient.spatch('oslc/workitems/'+ str(self.workitemid), json=js, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'});
def startWorking(self):
r = self.get_json('?oslc_cm.properties=rtc_cm:state{rdf:resource}')
r['rtc_cm:state']['rdf:resource'] = self.INPROGRESS
return self.jclient.sput('resource/itemName/com.ibm.team.workitem.WorkItem/'+ str(self.workitemid)+'?_action=com.ibm.team.workitem.taskWorkflow.action.startWorking', json=r, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
def stopWorking(self):
r = self.get_json('?oslc_cm.properties=rtc_cm:state{rdf:resource}')
r['rtc_cm:state']['rdf:resource'] = self.NEW
return self.jclient.sput('resource/itemName/com.ibm.team.workitem.WorkItem/'+ str(self.workitemid)+'?_action=com.ibm.team.workitem.taskWorkflow.action.stopWorking', json=r, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
def reopen(self):
r = self.get_json('?oslc_cm.properties=rtc_cm:state{rdf:resource}')
if r['rtc_cm:state']['rdf:resource'] == self.INVALID:
r['rtc_cm:state']['rdf:resource'] = self.NEW
return self.jclient.sput('resource/itemName/com.ibm.team.workitem.WorkItem/'+ str(self.workitemid)+'?_action=com.ibm.team.workitem.taskWorkflow.action.reopen', json=r, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
elif r['rtc_cm:state']['rdf:resource'] == self.DONE:
r['rtc_cm:state']['rdf:resource'] = self.INPROGRESS
return self.jclient.sput('resource/itemName/com.ibm.team.workitem.WorkItem/'+ str(self.workitemid)+'?_action=com.ibm.team.workitem.taskWorkflow.action.a1', json=r, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
def invalidate(self):
r = self.get_json('?oslc_cm.properties=rtc_cm:state{rdf:resource}')
r['rtc_cm:state']['rdf:resource'] = self.INVALID
return self.jclient.sput('resource/itemName/com.ibm.team.workitem.WorkItem/'+ str(self.workitemid)+'?_action=com.ibm.team.workitem.taskWorkflow.action.a2', json=r, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
def resolve(self):
r = self.get_json('?oslc_cm.properties=rtc_cm:state{rdf:resource}')
r['rtc_cm:state']['rdf:resource'] = self.DONE
return self.jclient.sput('resource/itemName/com.ibm.team.workitem.WorkItem/'+ str(self.workitemid)+'?_action=com.ibm.team.workitem.taskWorkflow.action.resolve', json=r, headers={'Content-Type': 'application/x-oslc-cm-change-request+json', 'Accept': 'text/json'})
def get_json(self, args = ""):
r = self.jclient.sget('oslc/workitems/'+ str(self.workitemid) +'.json'+args)
return json.loads(r.text)
def get_xml(self, args = ""):
r = self.jclient.sget('oslc/workitems/'+ str(self.workitemid) +'.xml'+args)
return r.text
class Task(Workitem):
TYPE = RTCClient.HOST+'oslc/types/'+RTCClient.PROJECT+'/task'
NEW = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.taskWorkflow/1'
INPROGRESS = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.taskWorkflow/2'
DONE = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.taskWorkflow/3'
INVALID = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.taskWorkflow/com.ibm.team.workitem.taskWorkflow.state.s4'
def getStateColor(self):
state = self.js['rtc_cm:state']['rdf:resource']
if state == self.NEW:
return cl.fg.purple
elif state == self.INPROGRESS:
return cl.fg.lightred
elif state == self.INVALID:
return cl.fg.lightgrey
elif state == self.DONE:
return cl.fg.green
class Story(Workitem):
TYPE = RTCClient.HOST+'oslc/types/'+RTCClient.PROJECT+'/com.ibm.team.apt.workItemType.story'
NEW = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.storyWorkflow/com.ibm.team.apt.story.idea'
IMPLEMENTED = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.storyWorkflow/com.ibm.team.apt.story.tested'
INPROGRESS = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.storyWorkflow/com.ibm.team.apt.story.defined'
DONE = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.storyWorkflow/com.ibm.team.apt.story.verified'
INVALID = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.storyWorkflow/com.ibm.team.apt.storyWorkflow.state.s2'
DEFERRED = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.storyWorkflow/com.ibm.team.apt.storyWorkflow.state.s1'
def getStateColor(self):
state = self.js['rtc_cm:state']['rdf:resource']
if state == self.NEW:
return cl.fg.purple
elif state == self.INPROGRESS:
return cl.fg.lightred
elif state == self.IMPLEMENTED:
return cl.fg.lightred
elif state == self.INVALID:
return cl.fg.lightgrey
elif state == self.DONE:
return cl.fg.green
elif state == self.DEFERRED:
return cl.fg.yellow
class Epic(Workitem):
TYPE = RTCClient.HOST+'oslc/types/'+RTCClient.PROJECT+'/com.ibm.team.apt.workItemType.epic'
NEW = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.epic.workflow/com.ibm.team.apt.epic.workflow.state.s1'
INPROGRESS = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.epic.workflow/com.ibm.team.apt.epic.workflow.state.s2'
DONE = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.epic.workflow/com.ibm.team.apt.epic.workflow.state.s3'
INVALID = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.epic.workflow/com.ibm.team.apt.epic.workflow.state.s6'
DEFERRED = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.apt.epic.workflow/com.ibm.team.apt.epic.workflow.state.s5'
def getStateColor(self):
state = self.js['rtc_cm:state']['rdf:resource']
if state == self.NEW:
return cl.fg.purple
elif state == self.INPROGRESS:
return cl.fg.lightred
elif state == self.INVALID:
return cl.fg.lightgrey
elif state == self.DONE:
return cl.fg.green
elif state == self.DEFERRED:
return cl.fg.yellow
class Defect(Workitem):
TYPE = RTCClient.HOST+'oslc/types/'+RTCClient.PROJECT+'/defect'
NEW = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.defectWorkflow/1'
INPROGRESS = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.defectWorkflow/2'
REOPENED = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.defectWorkflow/6'
RESOLVED = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.defectWorkflow/3'
VERIFIED = RTCClient.HOST+'oslc/workflows/'+RTCClient.PROJECT+'/states/com.ibm.team.workitem.defectWorkflow/4'
def getStateColor(self):
state = self.js['rtc_cm:state']['rdf:resource']
if state == self.NEW:
return cl.fg.purple
elif state == self.INPROGRESS:
return cl.fg.lightred
elif state == self.REOPENED:
return cl.fg.cyan
elif state == self.RESOLVED:
return cl.fg.lightred
elif state == self.VERIFIED:
return cl.fg.green
def user_search(client, pattern):
r = client.sget('oslc/users.json?oslc_cm.query=dc:title="*'+pattern+'*"')
return json.loads(r.text)
def query_search(client, pattern):
r = client.sget('oslc/queries.json?oslc_cm.query=rtc_cm:projectArea="'+RTCClient.PROJECT+'" and dc:creator="{currentUser}" and dc:title="*'+pattern+'*"')
return json.loads(r.text)
def print_queries(client, pattern):
print
print "Queries matching : "+cl.str(pattern, cl.fg.blue)
print " Created | Name | Description"
print "===================================================================================="
for u in query_search(client, pattern)['oslc_cm:results']:
print u['dc:modified'] + " | " + cl.str(u['dc:title'].ljust(32), cl.fg.green) +" | "+u['dc:description']
def print_users(client, pattern):
print
print "Users matching : "+cl.str(pattern, cl.fg.blue)
print " Created | Name | Email"
print "===================================================================================="
for u in user_search(client, pattern)['oslc_cm:results']:
print u['dc:modified'] + " | " + cl.str(u['dc:title'].ljust(32), cl.fg.green) +" | "+re.sub(r'mailto:([^%]+)%40(.*)',r'\1@\2',u['rtc_cm:emailAddress'])
def workitem_fromquery(client, query_str, isname = True, longdisplay = False, maxtitlelen = 80):
fields = 'oslc_cm.properties=dc:creator{dc:title},dc:type,rtc_cm:state,dc:identifier,dc:title,dc:modified,rtc_cm:ownedBy{dc:title}'
if isname:
query = query_search(client, query_str)['oslc_cm:results']
if not query:
return
query = query[0]
queryid = re.sub(r'.*/([^/]+)',r'\1',query['rdf:resource'])
workitems = Workitem.getList(client, 'oslc/queries/'+queryid+'/rtc_cm:results.json?'+fields)
print
print "Workitems for query : "+cl.str(query['dc:title'], cl.fg.blue)
else:
workitems = Workitem.getList(client, 'oslc/contexts/'+RTCClient.PROJECT+'/workitems.json?oslc_cm.query='+query_str+'&'+fields)
print
print "Workitems for query : "+cl.str(query_str, cl.fg.blue)
if not workitems:
return
maxlentitle = max([len(w.js['dc:title']) for w in workitems])
if maxlentitle > maxtitlelen:
maxlentitle = maxtitlelen
legend = " ID | "+"Title".ljust(maxlentitle, ' ') +" | Modified"
if longdisplay:
maxlencreator = max([len(w.js['dc:creator']['dc:title']) for w in workitems])
maxlenowner = max([len(w.js['rtc_cm:ownedBy']['dc:title']) for w in workitems])
legend = legend + " | "+"Creator".ljust(maxlencreator, ' ')+" | "+"Owner".ljust(maxlenowner, ' ')
print legend
separator = "========"+"".ljust(maxlentitle, '=')+"======================"
if longdisplay:
separator = separator + "======" + "".ljust(maxlencreator+maxlenowner, '=')
print separator
for w in workitems:
line = w.stateColorize(str(w.js['dc:identifier'])) +" | "+w.js['dc:title'].ljust(maxlentitle,' ')[:maxtitlelen]+ " | "+re.sub(r'([^T]+)T([^\.]+).*',r'\1 \2',w.js['dc:modified'])
if longdisplay:
line = line + " | " + w.js['dc:creator']['dc:title'].ljust(maxlencreator,' ') + " | " + w.js['rtc_cm:ownedBy']['dc:title'].ljust(maxlenowner,' ')
print line
def workitem_bytag(client, tag):
workitems = Workitem.getList(client, 'oslc/contexts/'+RTCClient.PROJECT+'/workitems.json?oslc_cm.query=oslc_cm:searchTerms="'+tag+'"')
print
print "workitems matching : "+cl.str(tag, cl.fg.blue)
print " ID | Title"
print "=================================================================="
for w in workitems:
print w.stateColorize(str(w.js['dc:identifier'])) + " | " + w.js['dc:title']
def workitem_details(client, workitemid):
wi = Workitem.getOne(client, workitemid, '?oslc_cm.properties=dc:identifier,\
dc:type{dc:title},dc:title,rdf:resource,dc:creator{dc:title},\
rtc_cm:ownedBy{dc:title},dc:description,rtc_cm:state{dc:title},\
rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent{dc:identifier,dc:title},\
rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.children,\
rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related')
print
print "=================================================================="
print "Workitem ID : " +cl.str(str(wi.js['dc:identifier']), cl.fg.green)+' ('+wi.js['dc:type']['dc:title']+')'
print "Title : " +cl.str(wi.js['dc:title'], cl.fg.red)
print "URL : " +wi.js['rdf:resource']
print "State : " +wi.stateColorize(wi.js['rtc_cm:state']['dc:title'])
print "Creator : " +wi.js['dc:creator']['dc:title']
print "Owner : " +wi.js['rtc_cm:ownedBy']['dc:title']
if len(wi.js['rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent']) != 0:
par = wi.js['rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent'][0]
print "Parent : " + str(par['dc:identifier'])+" ("+par['dc:title']+")"
if len(wi.js['rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.children']) != 0:
print "Child(ren) : " + reduce((lambda a, b: a +", "+ b), map((lambda a: re.sub(r'([^:]+): (.*)', r'\1 (\2)', a['oslc_cm:label'])), wi.js['rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.children']))
if len(wi.js['rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related']) != 0:
print "Related : " + reduce((lambda a, b: a +", "+ b), map((lambda a: re.sub(r'([^:]+): (.*)', r'\1 (\2)', a['oslc_cm:label'])), wi.js['rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related']))
print "Description :"
print html2text.html2text(wi.js['dc:description'])
comments = wi.get_comments()
if len(comments) == 0:
return
print "Comments :"
i = 0
for c in comments:
print str(i) + ": " +cl.str(c['dc:creator']['dc:title'], cl.fg.green)+" ("+c['dc:created'] + ") :"
print html2text.html2text(c['dc:description'])
i = i + 1
def workitem_comment(client, workitemid, comment):
workitem = Workitem.getOne(client, workitemid)
return workitem.add_comment(comment)
def workitem_create(client, title, description):
workitem = Workitem.createOne(client, title, description, Task.TYPE)
print "New item created with id : " + str(workitem.js['dc:identifier'])
return workitem
def workitem_edit(client, workitemid):
workitem = Workitem.getOne(client, workitemid, '?oslc_cm.properties=dc:identifier,dc:type,dc:title,dc:description,rtc_cm:ownedBy{dc:title}')
with tempfile.NamedTemporaryFile(suffix='workitem') as temp:
editor = os.environ.get('EDITOR','vim')
buf = json.dumps(workitem.js, indent = 2, separators=(',', ': '))
temp.write(buf)
temp.flush()
try:
subprocess.call([editor, temp.name])
except OSError:
print "'%s' can not be executed" % editor
sys.exit(1)
buf = open(temp.name, 'r').read()
js = json.loads(buf)
return workitem.change(js)
def workitem_set_parent(client, workitemid, parentid):
workitem = Workitem.getOne(client, workitemid)
if parentid is None:
js = { 'rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent': [] }
else:
parent = Workitem.getOne(client, parentid)
js = { 'rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent': [{ 'rdf:resource': parent.js['rdf:resource']}] }
return workitem.change(js)
def workitem_add_related(client, workitemid, relatedid):
workitem = Workitem.getOne(client, workitemid)
related = Workitem.getOne(client, relatedid)
js = { 'rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related': [{ 'rdf:resource': related.js['rdf:resource'], 'oslc_cm:label': str(relatedid)+': '+related.js['dc:title']}] }
js['rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related'].extend(workitem.js['rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related'])
return workitem.change(js)
def workitem_remove_related(client, workitemid, relatedid):
workitem = Workitem.getOne(client, workitemid)
related = Workitem.getOne(client, relatedid)
js = { 'rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related': [] }
for e in workitem.js['rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related']:
if e['rdf:resource'] == related.js['rdf:resource']:
continue
js['rtc_cm:com.ibm.team.workitem.linktype.relatedworkitem.related'].append({ 'rdf:resource': e['rdf:resource']})
return workitem.change(js)
def workitem_set_owner(client, workitemid, owner):
workitem = Workitem.getOne(client, workitemid)
users = user_search(client, owner)
if not users['oslc_cm:results']:
print "Unknown user: %s" % (owner)
sys.exit(1)
js = { 'rtc_cm:ownedBy': { 'rdf:resource': users['oslc_cm:results'][0]['rdf:resource'] } }
return workitem.change(js)
def main():
conffile = os.environ.get('HOME')+'/.rtcrc'
conf = ConfigParser.RawConfigParser(allow_no_value=True)
try:
with open(conffile) as f:
conf.readfp(f)
except IOError:
sample = """[auth]
# Specify your rtc id and password (yes in clear..)
id =
password =
[query]
default =
[display]
maxtitlelen =
"""
with open(conffile, "w") as f:
f.write (sample)
f.close()
os.chmod(conffile, 0600)
print "Config file sample written to "+conffile
conf.read(conffile)
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
parser.add_argument("-i", "--id", help="username id for login", default=conf.get('auth', 'id'), nargs=1, metavar=('<username>'))
parser.add_argument("--nocolor", help="turn off color in output", action="store_true")
parser.add_argument("-l", "--long", help="activate long display for workitem queries and search", action="store_true")
group.add_argument("-s", "--search", help="search pattern", nargs='+', metavar=('<pattern>'))
group.add_argument("-c", "--comment", help="additionnal comment", nargs=1, metavar=('[<comment>] <id> [<id> ...]'))
group.add_argument("-e", "--edit", help="edit some fields of a workitem", nargs=1, metavar=('<id> [<id> ...]'))
group.add_argument("-n", "--new", help="title of the new workitem", nargs=1, metavar=('<title> [<description>]'))
group.add_argument("-o", "--owner", help="name, firstname lastname, whatever that can match : 1st result will be used : check with -u", nargs=2, metavar=('<name>', '<id> [<id> ...]'))
group.add_argument("-p", "--parent", help="set option parameter to parent of the argument given", nargs=2, metavar=('<parent\'s id>', '<id> [<id> ...]'))
group.add_argument("--orphan", help="remove the parent of the workitem", nargs=1, metavar=('<id> [<id> ...]'))
group.add_argument("--related", help="add option parameter to related of the argument given", nargs=2, metavar=('<related\'s id>', '<id> [<id> ...]'))
group.add_argument("--removerelated", help="remove option parameter from related of the argument given", nargs=2, metavar=('<related\'s id>', '<id> [<id> ...]'))
group.add_argument("-u", "--user", help="search users for this pattern", nargs=1, metavar=('<pattern>'))
group.add_argument("--findquery", help="search queries for this pattern", nargs=1, metavar=('<pattern>'))
group.add_argument("-q", "--query", help="run query matching this pattern", nargs=1, metavar=('<query\'s name>'))
group.add_argument("--startworking", help="change state of workitem to : In Progress", nargs=1, metavar=('<id> [<id> ...]'))
group.add_argument("--stopworking", help="change state of workitem to : New", nargs=1, metavar=('<id> [<id> ...]'))
group.add_argument("--reopen", help="change state of workitem to : In Progress", nargs=1, metavar=('<id> [<id> ...]'))
group.add_argument("--invalidate", help="change state of workitem to : Invalid", nargs=1, metavar=('<id> [<id> ...]'))
group.add_argument("--resolve", help="change state of workitem to : Done", nargs=1, metavar=('<id> [<id> ...]'))
parser.add_argument("params", help=argparse.SUPPRESS, nargs='*', metavar=('<id>'))
args = parser.parse_args()
if args.id:
pw = conf.get('auth', 'password')
if not pw:
print "Id : "+args.id
pw = getpass.getpass()
client = RTCClient(args.id, pw)
else:
print "Please provide id on command line with --id or in "+conffile
sys.exit(1)
maxtitlelen = int(conf.get('display', 'maxtitlelen'))
if not maxtitlelen:
maxtitlelen = 80
if args.nocolor:
cl.colorize = False
if args.search:
for s in args.search:
workitem_fromquery(client, 'oslc_cm:searchTerms="'+s+'"', False, args.long, maxtitlelen)
elif args.orphan:
args.orphan.extend(args.params)
for s in args.orphan:
workitem_set_parent(client, s, None)
elif args.parent:
args.params.insert(0, args.parent[1])
for s in args.params:
workitem_set_parent(client, s, args.parent[0])
elif args.related:
args.params.insert(0, args.related[1])
for s in args.params:
workitem_add_related(client, s, args.related[0])
elif args.removerelated:
args.params.insert(0, args.removerelated[1])
for s in args.params:
workitem_remove_related(client, s, args.removerelated[0])
elif args.findquery:
if args.params:
parser.print_usage()
sys.exit(1)
print_queries(client, args.findquery[0])
elif args.query:
if args.params:
parser.print_usage()
sys.exit(1)
workitem_fromquery(client, args.query[0], True, args.long, maxtitlelen)
elif args.user:
if args.params:
parser.print_usage()
sys.exit(1)
print_users(client, args.user[0])
elif args.owner:
args.params.insert(0, args.owner[1])
for s in args.params:
workitem_set_owner(client, s, args.owner[0])
elif args.edit:
args.params.insert(0, args.edit[0])
for s in args.params:
workitem_edit(client, s)
elif args.startworking:
args.params.insert(0, args.startworking[0])
for s in args.params:
Workitem.getOne(client, s).startWorking()
elif args.stopworking:
args.params.insert(0, args.stopworking[0])
for s in args.params:
Workitem.getOne(client, s).stopWorking()
elif args.reopen:
args.params.insert(0, args.reopen[0])
for s in args.params:
Workitem.getOne(client, s).reopen()
elif args.invalidate:
args.params.insert(0, args.invalidate[0])
for s in args.params:
Workitem.getOne(client, s).invalidate()
elif args.resolve:
args.params.insert(0, args.resolve[0])
for s in args.params:
Workitem.getOne(client, s).resolve()
elif args.new:
desc = ""
if args.params:
if len(args.params) > 1:
parser.print_usage()
sys.exit(1)
desc = args.params[0]
workitem_create(client, args.new[0], desc)
elif args.comment:
comment = ""
if select.select([sys.stdin,],[],[],0.0)[0]:
for line in sys.stdin:
comment += line
comment = comment.strip()
args.params.insert(0, args.comment[0])
else:
comment = args.comment[0]
for s in args.params:
workitem_comment(client, s, comment)
elif len(args.params) == 0:
query = conf.get('query', 'default')
if query:
workitem_fromquery(client, query, True, args.long, maxtitlelen)
else:
workitem_fromquery(client, 'rtc_cm:ownedBy="{currentUser}" /sort=rtc_cm:state', False, args.long, maxtitlelen)
else: # there are some parameters provided without options
for s in args.params:
workitem_details(client, s)
sys.exit(0)
if __name__ == "__main__": main()