-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.py
More file actions
1728 lines (1453 loc) · 62.6 KB
/
api.py
File metadata and controls
1728 lines (1453 loc) · 62.6 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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# buildservice.py - Buildservice API support for Yabsc
#
# Copyright (C) 2008 James Oakley <jfunk@opensuse.org>
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import os
import re
import tempfile
import time
import urllib.request
import cgi
import xml.etree.cElementTree as ElementTree
from urllib.error import HTTPError
from osc import conf, core
from urllib.parse import quote, quote_plus
prj_template = """\
<project name="%(name)s">
<title>%(title)s</title>
<description>%(description)s</description>
%(maintainers)s
%(link)s
%(flags)s
%(repositories)s
</project>
"""
repo_template = """ <repository name="%(repository)s" %(mechanism)s block="%(block)s">
%(paths)s
%(archs)s
</repository>\n"""
path_template = '<path project="%(project)s" repository="%(repository)s"/>'
def flag2bool(flag):
"""
flag2bool(flag) -> Boolean
Returns a boolean corresponding to the string 'enable', or 'disable'
"""
if flag == 'enable':
return True
elif flag == 'disable':
return False
def bool2flag(b):
"""
bool2flag(b) -> String
Returns 'enable', or 'disable' according to boolean value b
"""
if b == True:
return 'enable'
elif b == False:
return 'disable'
class metafile:
"""
metafile(url, input, change_is_required=False, file_ext='.xml')
Implementation on osc.core.metafile that does not print to stdout
"""
def __init__(self, url, input, change_is_required=False, file_ext='.xml'):
self.url = url
self.change_is_required = change_is_required
(fd, self.filename) = tempfile.mkstemp(prefix = 'osc_metafile.', suffix = file_ext, dir = '/tmp')
f = os.fdopen(fd, 'w')
f.write(''.join(input))
f.close()
self.hash_orig = core.dgst(self.filename)
def sync(self):
hash = core.dgst(self.filename)
if self.change_is_required == True and hash == self.hash_orig:
os.unlink(self.filename)
return True
# don't do any exception handling... it's up to the caller what to do in case
# of an exception
core.http_PUT(self.url, file=self.filename)
os.unlink(self.filename)
return True
class BuildService():
"Interface to Build Service API"
def __init__(self, apiurl=None, oscrc=None):
try:
if oscrc:
conf.get_config(override_conffile = oscrc)
else:
conf.get_config()
except OSError as e:
if e.errno == 1:
# permission problem, should be the chmod(0600) issue
raise RuntimeError('Current user has no write permission for specified oscrc: %s' % oscrc)
raise # else
if apiurl:
self.apiurl = conf.config['apiurl_aliases'].get(apiurl, apiurl)
else:
self.apiurl = conf.config['apiurl']
if not self.apiurl:
raise RuntimeError('No apiurl "%s" found in %s' % (apiurl, oscrc))
# Add a couple of method aliases
self.copyPackage = core.copy_pac
self.addPerson = core.addPerson
def getAPIServerList(self):
"""getAPIServerList() -> list
Get list of API servers configured in .oscrc
"""
apiservers = []
for host in conf.config['api_host_options'].keys():
apiurl = "%s://%s" % (conf.config['scheme'], host)
return apiservers
# the following two alias api are added temporarily for compatible safe
def is_new_package(self, dst_project, dst_package):
return self.isNewPackage(dst_project, dst_package)
def gen_req_info(self, reqid, show_detail = True):
return self.genRequestInfo(reqid, show_detail)
def isNewPackage(self, dst_project, dst_package):
# Check whether the dst pac is a new one
new_pkg = False
try:
core.meta_exists(metatype = 'pkg',
path_args = (core.quote_plus(dst_project), core.quote_plus(dst_package)),
create_new = False,
apiurl = self.apiurl)
except urllib2.HTTPError as e:
if e.code == 404:
new_pkg = True
else:
raise e
return new_pkg
def createRequest(self, options_list, description, comment, supersede = False, **kwargs):
""" creates a request
options_list = a list of dicts, the valid keys in the dict depends
on the value of the 'action' key, see code below and
see osc/core.py. Additionally kwargs can contain the
following keywords, which gets passed through:
action = submit
opt_sourceupdate = cleanup|noupdate|update
acceptinfo_rev
acceptinfo_srcmd5
acceptinfo_xsrcmd5
acceptinfo_osrcmd5
acceptinfo_oxsrcmd5
opt_updatelink
action = maintenance_incident
opt_sourceupdate = cleanup|noupdate|update
supersede = shall old requests be superseded?
description = Description for the request, contains normally
the description why this request was done
comment = Comment in the state history
"""
commentElement = ElementTree.Element("comment")
commentElement.text = comment
state = ElementTree.Element("state")
state.set("name", "new")
state.append(commentElement)
request = core.Request()
request.description = description
request.state = core.RequestState(state)
supsersedereqs = []
for item in options_list:
if item['action'] == "submit":
request.add_action(item['action'],
src_project = item['src_project'],
src_package = item['src_package'],
tgt_project = item['tgt_project'],
tgt_package = item['tgt_package'],
src_rev = core.show_upstream_rev(self.apiurl, item['src_project'], item['src_package']),
**kwargs)
if supersede == True:
supsersedereqs.extend(core.get_exact_request_list(self.apiurl, item['src_project'],
item['tgt_project'], item['src_package'],
item['tgt_package'], req_type='submit',
req_state=['new','review', 'declined']))
elif item['action'] == "add_role":
request.add_action(item['action'],
tgt_project = item['tgt_project'],
tgt_package = item['tgt_package'],
person_name = item['person_name'],
person_role = item['person_role'],
group_name = item['group_name'],
group_role = item['group_role'])
elif item['action'] == "maintenance_release":
request.add_action(item['action'],
src_project = item['src_project'],
src_package = item['src_package'],
src_rev = item['src_rev'],
tgt_project = item['tgt_project'],
tgt_package = item['tgt_package'])
elif item['action'] == "maintenance_incident":
request.add_action(item['action'],
src_project = item['src_project'],
src_package = item['src_package'],
src_rev = item['src_rev'],
tgt_project = item['tgt_project'],
tgt_releaseproject
= item['tgt_releaseproject'],
person_name = item['person_name'],
**kwargs)
elif item['action'] == "delete":
request.add_action(item['action'],
tgt_project = item['tgt_project'],
tgt_package = item['tgt_package'])
if supersede == True:
supsersedereqs.extend(core.get_exact_request_list(self.apiurl, None,
item['tgt_project'], None,
item['tgt_package'], req_type='delete',
req_state=['new','review', 'declined']))
elif item['action'] == "change_devel":
request.add_action(item['action'],
src_project = item['src_project'],
src_package = item['src_package'],
tgt_project = item['tgt_project'],
tgt_package = item['tgt_package'])
else:
raise RuntimeError("Unknown Action: %s" % action)
request.create(self.apiurl)
if supersede == True and len(supsersedereqs) > 0:
processed = []
for req in supsersedereqs:
if req.reqid not in processed:
processed.append(req.reqid)
print("req.reqid: %s - new ID: %s\n"%(req.reqid, request.reqid))
core.change_request_state(self.apiurl, req.reqid,
'superseded',
'superseded by %s' % request.reqid,
request.reqid)
return request
def genRequestInfo(self, reqid, show_detail = True):
# helper routine to cat remote file
def get_source_file_content(apiurl, prj, pac, path, rev):
revision = core.show_upstream_xsrcmd5(apiurl, prj, pac, revision=rev)
if revision:
query = { 'rev': revision }
else:
query = None
u = core.makeurl(apiurl, ['source', prj, pac, core.pathname2url(path)], query=query)
content = ''
for buf in core.streamfile(u, core.http_GET, core.BUFSIZE):
content += buf
# return unicode str
return content.decode('utf8')
req = core.get_request(self.apiurl, reqid)
try:
reqinfo = unicode(req)
except UnicodeEncodeError:
reqinfo = u''
if not show_detail:
return reqinfo
src_project = req.actions[0].src_project
src_package = req.actions[0].src_package
tgt_project = req.actions[0].tgt_project
tgt_package = req.actions[0].tgt_package
src_rev = req.actions[0].src_rev
# Check whether the tgt pac is a new one
new_pkg = False
try:
core.meta_exists(metatype = 'pkg',
path_args = (core.quote_plus(tgt_project), core.quote_plus(tgt_package)),
create_new = False,
apiurl = self.apiurl)
except urllib2.HTTPError as e:
if e.code == 404:
new_pkg = True
else:
raise e
if new_pkg:
src_fl = core.meta_get_filelist(self.apiurl, src_project, src_package, expand=True, revision=src_rev)
spec_file = None
yaml_file = None
for f in src_fl:
if f.endswith(".spec"):
spec_file = f
elif f.endswith(".yaml"):
yaml_file = f
reqinfo += 'This is a NEW package in %s project.\n' % tgt_project
reqinfo += 'The files in the new package:\n'
reqinfo += '%s/\n' % src_package
reqinfo += ' |__ ' + '\n |__ '.join(src_fl)
if yaml_file:
reqinfo += '\n\nThe content of the YAML file, %s:\n' % (yaml_file)
reqinfo += '===================================================================\n'
reqinfo += get_source_file_content(self.apiurl, src_project, src_package, yaml_file, src_rev)
reqinfo += '\n===================================================================\n'
if spec_file:
reqinfo += '\n\nThe content of the spec file, %s:\n' % (spec_file)
reqinfo += '===================================================================\n'
reqinfo += get_source_file_content(self.apiurl, src_project, src_package, spec_file, src_rev)
reqinfo += '\n===================================================================\n'
else:
reqinfo += '\n\nspec file NOT FOUND!\n'
else:
try:
diff = core.server_diff(self.apiurl,
tgt_project, tgt_package, None,
src_project, src_package, src_rev, False)
try:
reqinfo += diff.decode('utf-8')
except UnicodeDecodeError:
try:
reqinfo += diff.decode('iso-8859-1')
except UnicodeDecodeError:
pass
except urllib2.HTTPError as e:
e.osc_msg = 'Diff not possible'
# the result, in unicode string
return reqinfo
def getUserData(self, user, *tags):
"""getUserData() -> str
Get the user data
"""
return core.get_user_data(self.apiurl, user, *tags)
def getUserName(self):
"""getUserName() -> str
Get the user name associated with the current API server
"""
return conf.config['api_host_options'][self.apiurl]['user']
def getProjectList(self):
"""getProjectList() -> list
Get list of projects
"""
return [project for project in core.meta_get_project_list(self.apiurl) if project != 'deleted']
def getWatchedProjectList(self):
"""getWatchedProjectList() -> list
Get list of watched projects
"""
username = self.getUserName()
tree = ElementTree.fromstring(''.join(core.get_user_meta(self.apiurl, username)))
projects = []
watchlist = tree.find('watchlist')
if watchlist:
for project in watchlist.findall('project'):
projects.append(project.get('name'))
homeproject = 'home:%s' % username
if not homeproject in projects and homeproject in self.getProjectList():
projects.append(homeproject)
return projects
def watchProject(self, project):
"""
watchProject(project)
Watch project
"""
username = self.getUserName()
data = core.meta_exists('user', username, create_new=False, apiurl=self.apiurl)
url = core.make_meta_url('user', username, self.apiurl)
person = ElementTree.fromstring(''.join(data))
watchlist = person.find('watchlist')
if not watchlist:
watchlist = ElementTree.SubElement(person, 'watchlist')
ElementTree.SubElement(watchlist, 'project', name=str(project))
f = metafile(url, ElementTree.tostring(person))
f.sync()
def unwatchProject(self, project):
"""
watchProject(project)
Watch project
"""
username = self.getUserName()
data = core.meta_exists('user', username, create_new=False, apiurl=self.apiurl)
url = core.make_meta_url('user', username, self.apiurl)
person = ElementTree.fromstring(''.join(data))
watchlist = person.find('watchlist')
for node in watchlist:
if node.get('name') == str(project):
watchlist.remove(node)
break
f = metafile(url, ElementTree.tostring(person))
f.sync()
def getRepoState(self, project):
targets = {}
results = core.show_prj_results_meta(self.apiurl, project)
if not results:
return {}
tree = ElementTree.fromstring(''.join(results))
for result in tree.findall('result'):
target = '%s/%s' % (result.get('repository'), result.get('arch'))
if result.get("dirty") == "true":
# If the repository is dirty state needs recalculation and
# cannot be trusted
state = "dirty"
else:
state = result.get('state')
targets[target] = state
return targets
def getResults(self, project):
"""getResults(project) -> (dict, list)
Get results of a project. Returns (results, targets)
results is a dict, with package names as the keys, and lists of result codes as the values
targets is a list of targets, corresponding to the result code lists
"""
results = core.show_prj_results_meta(self.apiurl, project)
tree = ElementTree.fromstring(''.join(results))
results = {}
targets = []
for result in tree.findall('result'):
targets.append('/'.join((result.get('repository'), result.get('arch'))))
for status in result.findall('status'):
package = status.get('package')
code = status.get('code')
if not package in results:
results[package] = []
results[package].append(code)
return (results, targets)
def getDiff(self, sprj, spkg, dprj, dpkg, rev):
diff = ''
diff += core.server_diff(self.apiurl, sprj, spkg, None,
dprj, dpkg, rev, False, True)
return diff
def getTargets(self, project):
"""
getTargets(project) -> list
Get a list of targets for a project
"""
targets = []
tree = ElementTree.fromstring(''.join(core.show_project_meta(self.apiurl, project)))
for repo in tree.findall('repository'):
for arch in repo.findall('arch'):
targets.append('%s/%s' % (repo.get('name'), arch.text))
return targets
def getPackageStatus(self, project, package):
"""
getPackageStatus(project, package) -> dict
Returns the status of a package as a dict with targets as the keys and status codes as the
values
"""
status = {}
tree = ElementTree.fromstring(''.join(core.show_results_meta(self.apiurl, project, package)))
for result in tree.findall('result'):
target = '/'.join((result.get('repository'), result.get('arch')))
statusnode = result.find('status')
if statusnode is not None:
code = statusnode.get('code')
details = statusnode.find('details')
if details is not None:
code += ': ' + details.text
else:
code = "unknown"
status[target] = code
return status
def getProjectDiff(self, src_project, dst_project):
packages = self.getPackageList(src_project)
for src_package in packages:
diff = core.server_diff(self.apiurl,
dst_project, src_package, None,
src_project, src_package, None, False)
print(diff)
def getPackageList(self, prj, deleted=None):
query = {}
if deleted:
query['deleted'] = 1
u = core.makeurl(self.apiurl, ['source', prj], query)
f = core.http_GET(u)
root = ElementTree.parse(f).getroot()
return [ node.get('name') for node in root.findall('entry') ]
def getBinaryList(self, project, target, package):
"""
getBinaryList(project, target, package) -> list
Returns a list of binaries for a particular target and package
"""
(repo, arch) = target.split('/')
return core.get_binarylist(self.apiurl, project, repo, arch, package)
def getBinary(self, project, target, package, file, path):
"""
getBinary(project, target, file, path)
Get binary 'file' for 'project' and 'target' and save it as 'path'
"""
(repo, arch) = target.split('/')
core.get_binary_file(self.apiurl, project, repo, arch, file, target_filename=path, package=package)
def getBinaryInfo(self, project, target, package, binary, ext=False):
"""
getBinaryInfo(project, target, package, binary, ext=False)
Get binary info for 'project', 'package' and 'target'
If ext=True get the info from build result (slower)
"""
(repo, arch) = target.split('/')
cmd = "?view=fileinfo"
if ext:
cmd += "_ext"
u = core.makeurl(self.apiurl, ['build', project, repo, arch,
package, binary, cmd])
f = core.http_GET(u)
fileinfo = ElementTree.parse(f).getroot()
result = {"provides": []}
for node in fileinfo.getchildren():
if node.tag == "provides":
result[node.tag].append(node.text)
else:
result[node.tag] = node.text
return result
def getBuildLog(self, project, target, package, offset=0):
"""
getBuildLog(project, target, package, offset=0) -> str
Returns the build log of a package for a particular target.
If offset is greater than 0, return only text after that offset. This allows live streaming
"""
(repo, arch) = target.split('/')
u = core.makeurl(self.apiurl, ['build', project, repo, arch, package, '_log?nostream=1&start=%s' % offset])
return core.http_GET(u).read()
def getWorkerStatus(self):
"""
getWorkerStatus() -> list of dicts
Get worker status as a list of dictionaries. Each dictionary contains the keys 'id',
'hostarch', and 'status'. If the worker is building, the dict will additionally contain the
keys 'project', 'package', 'target', and 'starttime'
"""
url = core.makeurl(self.apiurl, ['build', '_workerstatus'])
f = core.http_GET(url)
tree = ElementTree.parse(f).getroot()
workerstatus = []
for worker in tree.findall('building'):
d = {'id': worker.get('workerid'),
'status': 'building'}
for attr in ('hostarch', 'project', 'package', 'starttime'):
d[attr] = worker.get(attr)
d['target'] = '/'.join((worker.get('repository'), worker.get('arch')))
d['started'] = time.asctime(time.localtime(float(worker.get('starttime'))))
workerstatus.append(d)
for worker in tree.findall('idle'):
d = {'id': worker.get('workerid'),
'hostarch': worker.get('hostarch'),
'status': 'idle'}
workerstatus.append(d)
return workerstatus
def getWaitStats(self):
"""
getWaitStats() -> list
Returns the number of jobs in the wait queue as a list of (arch, count)
pairs
"""
url = core.makeurl(self.apiurl, ['build', '_workerstatus'])
f = core.http_GET(url)
tree = ElementTree.parse(f).getroot()
stats = []
for worker in tree.findall('waiting'):
stats.append((worker.get('arch'), int(worker.get('jobs'))))
return stats
def getSubmitRequests(self, req_state=None, start_time=None, end_time=None, projects=None):
"""
getSubmitRequests() -> list of dicts
"""
xpath = ''
xpath = core.xpath_join(xpath, 'action/@type=\'submit\'')
if req_state:
xpath = core.xpath_join(xpath, 'state/@name=\'%s\'' % req_state, op='and')
if projects:
xpath_base=''
#build list of projects
for i in projects:
xpath_base = core.xpath_join(xpath_base, 'action/target/@project=\'%s\'' % i, op='or')
xpath = core.xpath_join(xpath, xpath_base, op='and', nexpr_parentheses=True)
url = core.makeurl(self.apiurl, ['search', 'request', '?match=%s' %quote_plus(xpath)])
f = core.http_GET(url)
tree = ElementTree.parse(f).getroot()
submitrequests = []
for req in tree.findall('request'):
state = req.find('state')
if req_state and state.get('name') != req_state:
continue
if start_time and state.get('when') < start_time:
continue
if end_time and state.get('when') >= end_time:
continue
for action in req.findall('action'):
if action.get('type') != "submit":
continue
d = {'id': int(req.get('id'))}
src = action.find('source')
d['srcproject'] = src.get('project')
d['srcpackage'] = src.get('package')
dest = action.find('target')
d['dstproject'] = dest.get('project')
d['dstpackage'] = dest.get('package')
d['state'] = state.get('name')
d['when'] = state.get('when')
submitrequests.append(d)
submitrequests.sort(key=lambda x: x['id'])
return submitrequests
def rebuild(self, project, package, target=None, code=None):
"""
rebuild(project, package, target, code=None)
Rebuild 'package' in 'project' for 'target'. If 'code' is specified,
all targets with that code will be rebuilt
"""
if target:
(repo, arch) = target.split('/')
else:
repo = None
arch = None
return core.rebuild(self.apiurl, project, package, repo, arch, code)
def abortBuild(self, project, package=None, target=None):
"""
abort(project, package=None, target=None)
Abort build of a package or all packages in a project
"""
if target:
(repo, arch) = target.split('/')
else:
repo = None
arch = None
return core.abortbuild(self.apiurl, project, package, arch, repo)
def getBuildHistory(self, project, package, target):
"""
getBuildHistory(project, package, target) -> list
Get build history of package for target as a list of tuples of the form
(time, srcmd5, rev, versrel, bcnt)
"""
(repo, arch) = target.split('/')
u = core.makeurl(self.apiurl, ['build', project, repo, arch, package, '_history'])
f = core.http_GET(u)
root = ElementTree.parse(f).getroot()
r = []
for node in root.findall('entry'):
rev = int(node.get('rev'))
srcmd5 = node.get('srcmd5')
versrel = node.get('versrel')
bcnt = int(node.get('bcnt'))
t = time.localtime(int(node.get('time')))
t = time.strftime('%Y-%m-%d %H:%M:%S', t)
r.append((t, srcmd5, rev, versrel, bcnt))
return r
def getCommitLog(self, project, package, revision=None):
"""
getCommitLog(project, package, revision=None) -> list
Get commit log for package in project. If revision is set, get just the
log for that revision.
Each log is a tuple of the form (rev, srcmd5, version, time, user,
comment)
"""
u = core.makeurl(self.apiurl, ['source', project, package, '_history'])
f = core.http_GET(u)
root = ElementTree.parse(f).getroot()
r = []
revisions = root.findall('revision')
revisions.reverse()
for node in revisions:
rev = int(node.get('rev'))
if revision and rev != int(revision):
continue
srcmd5 = node.find('srcmd5').text
version = node.find('version').text
user = node.find('user').text
try:
comment = node.find('comment').text
except:
comment = '<no message>'
t = time.localtime(int(node.find('time').text))
t = time.strftime('%Y-%m-%d %H:%M:%S', t)
r.append((rev, srcmd5, version, t, user, comment))
return r
def getProjectMeta(self, project):
"""
getProjectMeta(project) -> string
Get XML metadata for project
"""
return ''.join(core.show_project_meta(self.apiurl, project))
def getProjectData(self, project, tag):
"""
getProjectData(project, tag) -> list
Return a string list if node has text, else return the values dict list
"""
data = []
tree = ElementTree.fromstring(self.getProjectMeta(project))
nodes = tree.findall(tag)
if nodes:
for node in nodes:
node_value = {}
for key in node.keys():
node_value[key] = node.get(key)
if node_value:
data.append(node_value)
else:
data.append(node.text)
return data
def getProjectPersons(self, project, role):
"""
getProjectPersons(project, role) -> list
Return a userid list in this project with this role
"""
userids = []
persons = self.getProjectData(project, 'person')
for person in persons:
if person.has_key('role') and person['role'] == role:
userids.append(person['userid'])
return userids
def getProjectDevel(self, project):
"""
getProjectDevel(project) -> tuple (devel_prj, devel_pkg)
Return the devel tuple of a project if it has the node, else return None
"""
devels = self.getProjectData(project, 'devel')
for devel in devels:
if devel.has_key('project') and devel.has_key('package'):
return (devel['project'], devel['package'])
return None
def deleteProject(self, project):
"""
deleteProject(project)
Delete the specific project
"""
try:
core.delete_project(self.apiurl, project)
except Exception:
return False
return True
def getPackageMeta(self, project, package):
"""
getPackageMeta(project, package) -> string
Get XML metadata for package in project
"""
return ''.join(core.show_package_meta(self.apiurl, project, package))
def getPackageData(self, project, package, tag):
"""
getPackageData(project, package, tag) -> list
Return a string list if node has text, else return the values dict list
"""
data = []
tree = ElementTree.fromstring(self.getPackageMeta(project, package))
nodes = tree.findall(tag)
if nodes:
for node in nodes:
node_value = {}
for key in node.keys():
node_value[key] = node.get(key)
if node_value:
data.append(node_value)
else:
data.append(node.text)
return data
def getPackagePersons(self, project, package, role):
"""
getPackagePersons(project, package, role) -> list
Return a userid list in the package with this role
"""
userids = []
persons = self.getPackageData(project, package, 'person')
for person in persons:
if person.has_key('role') and person['role'] == role:
userids.append(person['userid'])
return userids
def getPackageDevel(self, project, package):
"""
getPackageDevel(project, package) -> tuple (devel_prj, devel_pkg)
Return the devel tuple of a package if it has the node, else return None
"""
devels = self.getPackageData(project, package, 'devel')
for devel in devels:
if devel.has_key('project') and devel.has_key('package'):
return (devel['project'], devel['package'])
return None
def deletePackage(self, project, package):
"""
deletePackage(project, package)
Delete the specific package in project
"""
try:
core.delete_package(self.apiurl, project, package)
except Exception:
return False
return True
def projectFlags(self, project):
"""
projectFlags(project) -> ProjectFlags
Return a ProjectFlags object for manipulating the flags of project
"""
return ProjectFlags(self, project)
def getUserEmail(self, user):
"""
getUserEmail(userid) -> string
Get email of a user ID
"""
user_data = self.getUserData(user, "email")
if user_data:
return user_data[0]
else:
return ""
def getProjectMaintainers(self, project):
"""
getProjectMaintainers(project) -> list
Get a list of userids who are maintainers of a project
"""
tree = ElementTree.fromstring(''.join(core.show_project_meta(self.apiurl,
project)))
maintainers = []
for person in tree.findall('person'):
if person.get('role') == "maintainer":
maintainers.append(person.get('userid'))
return maintainers
def isMaintainer(self, project, user):
"""
isMaintainer(project, user) -> Bool
returns True if the user is a maintainer in the project False otherwise
"""
maintainers = self.getProjectMaintainers(project)
if user in maintainers:
return True
return False
def getPackageChecksum(self, project, package, rev=None):
"""
getPackageChecksum(self, project, package, rev=None) -> string
returns source md5 of a package or None if it can't be determined atm
"""
query = { 'expand' : 1 }
if rev:
query['rev'] = rev
else:
query['rev'] = 'latest'
u = core.makeurl(self.apiurl, ['source', project, package], query=query)
try:
f = core.http_GET(u)
except HTTPError as e:
if e.code == 400 and re.match('service .+ failed', e.reason):
return None
else:
raise
root = ElementTree.parse(f).getroot()
return root.get("srcmd5")
def hasChanges(self, oprj, opkg, orev, tprj, tpkg):
"""
hasChanges(self, oprj, opkg, orev, tprj, tpkg) -> Bool