-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathbase.py
More file actions
1862 lines (1565 loc) · 64.8 KB
/
base.py
File metadata and controls
1862 lines (1565 loc) · 64.8 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
# base.py - the base classes etc. for a Python interface to bugzilla
#
# Copyright (C) 2007, 2008, 2009, 2010 Red Hat Inc.
# Author: Will Woods <[email protected]>
#
# 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. See http://www.gnu.org/copyleft/gpl.html for
# the full text of the license.
import collections
import getpass
import locale
from logging import getLogger
import os
import sys
from io import BytesIO
# pylint: disable=import-error
if sys.version_info[0] >= 3:
# pylint: disable=no-name-in-module
from configparser import SafeConfigParser
from http.cookiejar import LoadError, MozillaCookieJar
from urllib.parse import urlparse, parse_qsl
from xmlrpc.client import Binary, Fault
else:
from ConfigParser import SafeConfigParser
from cookielib import LoadError, MozillaCookieJar
from urlparse import urlparse, parse_qsl
from xmlrpclib import Binary, Fault
# pylint: enable=import-error
from .apiversion import __version__
from .bug import Bug, User
from .transport import BugzillaError, _BugzillaServerProxy, _RequestsTransport
log = getLogger(__name__)
mimemagic = None
def _detect_filetype(fname):
global mimemagic
if mimemagic is None:
try:
# pylint: disable=import-error
import magic
mimemagic = magic.open(getattr(magic, "MAGIC_MIME_TYPE", 16))
mimemagic.load()
except ImportError as e:
log.debug("Could not load python-magic: %s", e)
mimemagic = None
if not mimemagic:
return None
if not os.path.isabs(fname):
return None
try:
return mimemagic.file(fname)
except Exception as e:
log.debug("Could not detect content_type: %s", e)
return None
def _nested_update(d, u):
# Helper for nested dict update()
# https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
for k, v in list(u.items()):
if isinstance(v, collections.Mapping):
d[k] = _nested_update(d.get(k, {}), v)
else:
d[k] = v
return d
def _default_auth_location(filename):
"""
Determine auth location for filename, like 'bugzillacookies'. If
old style ~/.bugzillacookies exists, we use that, otherwise we
use ~/.cache/python-bugzilla/bugzillacookies. Same for bugzillatoken
"""
homepath = os.path.expanduser("~/.%s" % filename)
xdgpath = os.path.expanduser("~/.cache/python-bugzilla/%s" % filename)
if os.path.exists(xdgpath):
return xdgpath
if os.path.exists(homepath):
return homepath
if not os.path.exists(os.path.dirname(xdgpath)):
os.makedirs(os.path.dirname(xdgpath), 0o700)
return xdgpath
def _build_cookiejar(cookiefile):
cj = MozillaCookieJar(cookiefile)
if cookiefile is None:
return cj
if not os.path.exists(cookiefile):
# Make sure a new file has correct permissions
open(cookiefile, 'a').close()
os.chmod(cookiefile, 0o600)
cj.save()
return cj
try:
cj.load()
return cj
except LoadError:
raise BugzillaError("cookiefile=%s not in Mozilla format" %
cookiefile)
_default_configpaths = [
'/etc/bugzillarc',
'~/.bugzillarc',
'~/.config/python-bugzilla/bugzillarc',
]
def _open_bugzillarc(configpaths=-1):
if configpaths == -1:
configpaths = _default_configpaths[:]
# pylint: disable=protected-access
configpaths = [os.path.expanduser(p) for p in
Bugzilla._listify(configpaths)]
# pylint: enable=protected-access
cfg = SafeConfigParser()
read_files = cfg.read(configpaths)
if not read_files:
return
log.info("Found bugzillarc files: %s", read_files)
return cfg
class _FieldAlias(object):
"""
Track API attribute names that differ from what we expose in users.
For example, originally 'short_desc' was the name of the property that
maps to 'summary' on modern bugzilla. We want pre-existing API users
to be able to continue to use Bug.short_desc, and
query({"short_desc": "foo"}). This class tracks that mapping.
@oldname: The old attribute name
@newname: The modern attribute name
@is_api: If True, use this mapping for values sent to the xmlrpc API
(like the query example)
@is_bug: If True, use this mapping for Bug attribute names.
"""
def __init__(self, newname, oldname, is_api=True, is_bug=True):
self.newname = newname
self.oldname = oldname
self.is_api = is_api
self.is_bug = is_bug
class _BugzillaAPICache(object):
"""
Helper class that holds cached API results for things like products,
components, etc.
"""
def __init__(self):
self.products = []
self.component_names = {}
self.bugfields = []
class Bugzilla(object):
"""
The main API object. Connects to a bugzilla instance over XMLRPC, and
provides wrapper functions to simplify dealing with API calls.
The most common invocation here will just be with just a URL:
bzapi = Bugzilla("http://bugzilla.example.com")
If you have previously logged into that URL, and have cached login
cookies/tokens, you will automatically be logged in. Otherwise to
log in, you can either pass auth options to __init__, or call a login
helper like interactive_login().
If you are not logged in, you won be able to access restricted data like
user email, or perform write actions like bug create/update. But simple
querys will work correctly.
If you are unsure if you are logged in, you can check the .logged_in
property.
Another way to specify auth credentials is via a 'bugzillarc' file.
See readconfig() documentation for details.
"""
# bugzilla version that the class is targeting. filled in by
# subclasses
bz_ver_major = 0
bz_ver_minor = 0
@staticmethod
def url_to_query(url):
"""
Given a big huge bugzilla query URL, returns a query dict that can
be passed along to the Bugzilla.query() method.
"""
q = {}
# pylint: disable=unpacking-non-sequence
(ignore, ignore, path,
ignore, query, ignore) = urlparse(url)
base = os.path.basename(path)
if base not in ('buglist.cgi', 'query.cgi'):
return {}
for (k, v) in parse_qsl(query):
if k not in q:
q[k] = v
elif isinstance(q[k], list):
q[k].append(v)
else:
oldv = q[k]
q[k] = [oldv, v]
# Handle saved searches
if base == "buglist.cgi" and "namedcmd" in q and "sharer_id" in q:
q = {
"sharer_id": q["sharer_id"],
"savedsearch": q["namedcmd"],
}
return q
@staticmethod
def fix_url(url):
"""
Turn passed url into a bugzilla XMLRPC web url
"""
if '://' not in url:
log.debug('No scheme given for url, assuming https')
url = 'https://' + url
if url.count('/') < 3:
log.debug('No path given for url, assuming /xmlrpc.cgi')
url = url + '/xmlrpc.cgi'
return url
@staticmethod
def _listify(val):
if val is None:
return val
if isinstance(val, list):
return val
return [val]
def __init__(self, url=-1, user=None, password=None, cookiefile=-1,
sslverify=True, tokenfile=-1, use_creds=True, api_key=None,
cert=None):
"""
:param url: The bugzilla instance URL, which we will connect
to immediately. Most users will want to specify this at
__init__ time, but you can defer connecting by passing
url=None and calling connect(URL) manually
:param user: optional username to connect with
:param password: optional password for the connecting user
:param cert: optional certificate file for client side certificate
authentication
:param cookiefile: Location to cache the login session cookies so you
don't have to keep specifying username/password. Bugzilla 5+ will
use tokens instead of cookies.
If -1, use the default path. If None, don't use or save
any cookiefile.
:param sslverify: Set this to False to skip SSL hostname and CA
validation checks, like out of date certificate
:param tokenfile: Location to cache the API login token so youi
don't have to keep specifying username/password.
If -1, use the default path. If None, don't use
or save any tokenfile.
:param use_creds: If False, this disables cookiefile, tokenfile,
and any bugzillarc reading. This overwrites any tokenfile
or cookiefile settings
:param sslverify: Maps to 'requests' sslverify parameter. Set to
False to disable SSL verification, but it can also be a path
to file or directory for custom certs.
:param api_key: A bugzilla
"""
if url == -1:
raise TypeError("Specify a valid bugzilla url, or pass url=None")
# Settings the user might want to tweak
self.user = user or ''
self.password = password or ''
self.api_key = api_key
self.cert = cert or ''
self.url = ''
self._proxy = None
self._transport = None
self._cookiejar = None
self._sslverify = sslverify
self._cache = _BugzillaAPICache()
self._bug_autorefresh = False
self._field_aliases = []
self._init_field_aliases()
self.configpath = _default_configpaths[:]
if not use_creds:
cookiefile = None
tokenfile = None
self.configpath = []
if cookiefile == -1:
cookiefile = _default_auth_location("bugzillacookies")
if tokenfile == -1:
tokenfile = _default_auth_location("bugzillatoken")
log.debug("Using tokenfile=%s", tokenfile)
self.cookiefile = cookiefile
self.tokenfile = tokenfile
if url:
self.connect(url)
self._init_class_from_url()
self._init_class_state()
def _init_class_from_url(self):
"""
Detect if we should use RHBugzilla class, and if so, set it
"""
from bugzilla import RHBugzilla
if isinstance(self, RHBugzilla):
return
c = None
if "bugzilla.redhat.com" in self.url:
log.info("Using RHBugzilla for URL containing bugzilla.redhat.com")
c = RHBugzilla
else:
try:
extensions = self._proxy.Bugzilla.extensions()
if "RedHat" in extensions.get('extensions', {}):
log.info("Found RedHat bugzilla extension, "
"using RHBugzilla")
c = RHBugzilla
except Fault:
log.debug("Failed to fetch bugzilla extensions", exc_info=True)
if not c:
return
self.__class__ = c
def _init_class_state(self):
"""
Hook for subclasses to do any __init__ time setup
"""
pass
def _init_field_aliases(self):
# List of field aliases. Maps old style RHBZ parameter
# names to actual upstream values. Used for createbug() and
# query include_fields at least.
self._add_field_alias('summary', 'short_desc')
self._add_field_alias('description', 'comment')
self._add_field_alias('platform', 'rep_platform')
self._add_field_alias('severity', 'bug_severity')
self._add_field_alias('status', 'bug_status')
self._add_field_alias('id', 'bug_id')
self._add_field_alias('blocks', 'blockedby')
self._add_field_alias('blocks', 'blocked')
self._add_field_alias('depends_on', 'dependson')
self._add_field_alias('creator', 'reporter')
self._add_field_alias('url', 'bug_file_loc')
self._add_field_alias('dupe_of', 'dupe_id')
self._add_field_alias('dupe_of', 'dup_id')
self._add_field_alias('comments', 'longdescs')
self._add_field_alias('creation_time', 'opendate')
self._add_field_alias('creation_time', 'creation_ts')
self._add_field_alias('whiteboard', 'status_whiteboard')
self._add_field_alias('last_change_time', 'delta_ts')
def _get_user_agent(self):
return 'python-bugzilla/%s' % __version__
user_agent = property(_get_user_agent)
###################
# Private helpers #
###################
def _check_version(self, major, minor):
"""
Check if the detected bugzilla version is >= passed major/minor pair.
"""
if major < self.bz_ver_major:
return True
if (major == self.bz_ver_major and minor <= self.bz_ver_minor):
return True
return False
def _add_field_alias(self, *args, **kwargs):
self._field_aliases.append(_FieldAlias(*args, **kwargs))
def _get_bug_aliases(self):
return [(f.newname, f.oldname)
for f in self._field_aliases if f.is_bug]
def _get_api_aliases(self):
return [(f.newname, f.oldname)
for f in self._field_aliases if f.is_api]
###################
# Cookie handling #
###################
def _getcookiefile(self):
"""
cookiefile is the file that bugzilla session cookies are loaded
and saved from.
"""
return self._cookiejar.filename
def _delcookiefile(self):
self._cookiejar = None
def _setcookiefile(self, cookiefile):
if (self._cookiejar and cookiefile == self._cookiejar.filename):
return
if self._proxy is not None:
raise RuntimeError("Can't set cookies with an open connection, "
"disconnect() first.")
log.debug("Using cookiefile=%s", cookiefile)
self._cookiejar = _build_cookiejar(cookiefile)
cookiefile = property(_getcookiefile, _setcookiefile, _delcookiefile)
#############################
# Login/connection handling #
#############################
def readconfig(self, configpath=None):
"""
:param configpath: Optional bugzillarc path to read, instead of
the default list.
This function is called automatically from Bugzilla connect(), which
is called at __init__ if a URL is passed. Calling it manually is
just for passing in a non-standard configpath.
The locations for the bugzillarc file are preferred in this order:
~/.config/python-bugzilla/bugzillarc
~/.bugzillarc
/etc/bugzillarc
It has content like:
[bugzilla.yoursite.com]
user = username
password = password
Or
[bugzilla.yoursite.com]
api_key = key
The file can have multiple sections for different bugzilla instances.
A 'url' field in the [DEFAULT] section can be used to set a default
URL for the bugzilla command line tool.
Be sure to set appropriate permissions on bugzillarc if you choose to
store your password in it!
"""
cfg = _open_bugzillarc(configpath or self.configpath)
if not cfg:
return
section = ""
log.debug("bugzillarc: Searching for config section matching %s",
self.url)
for s in sorted(cfg.sections()):
# Substring match - prefer the longest match found
if s in self.url:
log.debug("bugzillarc: Found matching section: %s", s)
section = s
if not section:
log.debug("bugzillarc: No section found")
return
for key, val in cfg.items(section):
if key == "api_key":
log.debug("bugzillarc: setting api_key")
self.api_key = val
elif key == "user":
log.debug("bugzillarc: setting user=%s", val)
self.user = val
elif key == "password":
log.debug("bugzillarc: setting password")
self.password = val
elif key == "cert":
log.debug("bugzillarc: setting cert")
self.cert = val
else:
log.debug("bugzillarc: unknown key=%s", key)
def _set_bz_version(self, version):
try:
self.bz_ver_major, self.bz_ver_minor = [
int(i) for i in version.split(".")[0:2]]
except Exception:
log.debug("version doesn't match expected format X.Y.Z, "
"assuming 5.0", exc_info=True)
self.bz_ver_major = 5
self.bz_ver_minor = 0
def connect(self, url=None):
"""
Connect to the bugzilla instance with the given url. This is
called by __init__ if a URL is passed. Or it can be called manually
at any time with a passed URL.
This will also read any available config files (see readconfig()),
which may set 'user' and 'password', and others.
If 'user' and 'password' are both set, we'll run login(). Otherwise
you'll have to login() yourself before some methods will work.
"""
if self._transport:
self.disconnect()
if url is None and self.url:
url = self.url
url = self.fix_url(url)
self._transport = _RequestsTransport(
url, self._cookiejar, sslverify=self._sslverify, cert=self.cert)
self._transport.user_agent = self.user_agent
self._proxy = _BugzillaServerProxy(url, self.tokenfile,
self._transport)
self.url = url
# we've changed URLs - reload config
self.readconfig()
if (self.user and self.password):
log.info("user and password present - doing login()")
self.login()
if self.api_key:
log.debug("using API key")
self._proxy.use_api_key(self.api_key)
version = self._proxy.Bugzilla.version()["version"]
log.debug("Bugzilla version string: %s", version)
self._set_bz_version(version)
def disconnect(self):
"""
Disconnect from the given bugzilla instance.
"""
self._proxy = None
self._transport = None
self._cache = _BugzillaAPICache()
def _login(self, user, password):
"""
Backend login method for Bugzilla3
"""
return self._proxy.User.login({'login': user, 'password': password})
def _logout(self):
"""
Backend login method for Bugzilla3
"""
return self._proxy.User.logout()
def login(self, user=None, password=None):
"""
Attempt to log in using the given username and password. Subsequent
method calls will use this username and password. Returns False if
login fails, otherwise returns some kind of login info - typically
either a numeric userid, or a dict of user info.
If user is not set, the value of Bugzilla.user will be used. If *that*
is not set, ValueError will be raised. If login fails, BugzillaError
will be raised.
This method will be called implicitly at the end of connect() if user
and password are both set. So under most circumstances you won't need
to call this yourself.
"""
if self.api_key:
raise ValueError("cannot login when using an API key")
if user:
self.user = user
if password:
self.password = password
if not self.user:
raise ValueError("missing username")
if not self.password:
raise ValueError("missing password")
try:
ret = self._login(self.user, self.password)
self.password = ''
log.info("login successful for user=%s", self.user)
return ret
except Fault as e:
raise BugzillaError("Login failed: %s" % str(e.faultString))
def interactive_login(self, user=None, password=None, force=False):
"""
Helper method to handle login for this bugzilla instance.
:param user: bugzilla username. If not specified, prompt for it.
:param password: bugzilla password. If not specified, prompt for it.
:param force: Unused
"""
ignore = force
log.debug('Calling interactive_login')
if not user:
sys.stdout.write('Bugzilla Username: ')
sys.stdout.flush()
user = sys.stdin.readline().strip()
if not password:
password = getpass.getpass('Bugzilla Password: ')
log.info('Logging in... ')
self.login(user, password)
log.info('Authorization cookie received.')
def logout(self):
"""
Log out of bugzilla. Drops server connection and user info, and
destroys authentication cookies.
"""
self._logout()
self.disconnect()
self.user = ''
self.password = ''
@property
def logged_in(self):
"""
This is True if this instance is logged in else False.
We test if this session is authenticated by calling the User.get()
XMLRPC method with ids set. Logged-out users cannot pass the 'ids'
parameter and will result in a 505 error. If we tried to login with a
token, but the token was incorrect or expired, the server returns a
32000 error.
For Bugzilla 5 and later, a new method, User.valid_login is available
to test the validity of the token. However, this will require that the
username be cached along with the token in order to work effectively in
all scenarios and is not currently used. For more information, refer to
the following url.
http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login
"""
try:
self._proxy.User.get({'ids': []})
return True
except Fault as e:
if e.faultCode == 505 or e.faultCode == 32000:
return False
raise e
######################
# Bugfields querying #
######################
def _getbugfields(self):
"""
Get the list of valid fields for Bug objects
"""
r = self._proxy.Bug.fields({'include_fields': ['name']})
return [f['name'] for f in r['fields']]
def getbugfields(self, force_refresh=False):
"""
Calls getBugFields, which returns a list of fields in each bug
for this bugzilla instance. This can be used to set the list of attrs
on the Bug object.
"""
if force_refresh or not self._cache.bugfields:
log.debug("Refreshing bugfields")
self._cache.bugfields = self._getbugfields()
self._cache.bugfields.sort()
log.debug("bugfields = %s", self._cache.bugfields)
return self._cache.bugfields
bugfields = property(fget=lambda self: self.getbugfields(),
fdel=lambda self: setattr(self, '_bugfields', None))
####################
# Product querying #
####################
def product_get(self, ids=None, names=None,
include_fields=None, exclude_fields=None,
ptype=None):
"""
Raw wrapper around Product.get
https://bugzilla.readthedocs.io/en/latest/api/core/v1/product.html#get-product
This does not perform any caching like other product API calls.
If ids, names, or ptype is not specified, we default to
ptype=accessible for historical reasons
@ids: List of product IDs to lookup
@names: List of product names to lookup
@ptype: Either 'accessible', 'selectable', or 'enterable'. If
specified, we return data for all those
@include_fields: Only include these fields in the output
@exclude_fields: Do not include these fields in the output
"""
if ids is None and names is None and ptype is None:
ptype = "accessible"
if ptype:
raw = None
if ptype == "accessible":
raw = self._proxy.Product.get_accessible_products()
elif ptype == "selectable":
raw = self._proxy.Product.get_selectable_products()
elif ptype == "enterable":
raw = self._proxy.Product.get_enterable_products()
if raw is None:
raise RuntimeError("Unknown ptype=%s" % ptype)
ids = raw['ids']
log.debug("For ptype=%s found ids=%s", ptype, ids)
kwargs = {}
if ids:
kwargs["ids"] = self._listify(ids)
if names:
kwargs["names"] = self._listify(names)
if include_fields:
kwargs["include_fields"] = include_fields
if exclude_fields:
kwargs["exclude_fields"] = exclude_fields
ret = self._proxy.Product.get(kwargs)
return ret['products']
def refresh_products(self, **kwargs):
"""
Refresh a product's cached info. Basically calls product_get
with the passed arguments, and tries to intelligently update
our product cache.
For example, if we already have cached info for product=foo,
and you pass in names=["bar", "baz"], the new cache will have
info for products foo, bar, baz. Individual product fields are
also updated.
"""
for product in self.product_get(**kwargs):
updated = False
for current in self._cache.products[:]:
if (current.get("id", -1) != product.get("id", -2) and
current.get("name", -1) != product.get("name", -2)):
continue
_nested_update(current, product)
updated = True
break
if not updated:
self._cache.products.append(product)
def getproducts(self, force_refresh=False, **kwargs):
"""
Query all products and return the raw dict info. Takes all the
same arguments as product_get.
On first invocation this will contact bugzilla and internally
cache the results. Subsequent getproducts calls or accesses to
self.products will return this cached data only.
:param force_refresh: force refreshing via refresh_products()
"""
if force_refresh or not self._cache.products:
self.refresh_products(**kwargs)
return self._cache.products
products = property(
fget=lambda self: self.getproducts(),
fdel=lambda self: setattr(self, '_products', None),
doc="Helper for accessing the products cache. If nothing "
"has been cached yet, this calls getproducts()")
#######################
# components querying #
#######################
def _lookup_product_in_cache(self, productname):
prodstr = isinstance(productname, str) and productname or None
prodint = isinstance(productname, int) and productname or None
for proddict in self._cache.products:
if prodstr == proddict.get("name", -1):
return proddict
if prodint == proddict.get("id", "nope"):
return proddict
return {}
def getcomponentsdetails(self, product, force_refresh=False):
"""
Wrapper around Product.get(include_fields=["components"]),
returning only the "components" data for the requested product,
slightly reworked to a dict mapping of components.name: components,
for historical reasons.
This uses the product cache, but will update it if the product
isn't found or "components" isn't cached for the product.
In cases like bugzilla.redhat.com where there are tons of
components for some products, this API will time out. You
should use product_get instead.
"""
proddict = self._lookup_product_in_cache(product)
if (force_refresh or not proddict or "components" not in proddict):
self.refresh_products(names=[product],
include_fields=["name", "id", "components"])
proddict = self._lookup_product_in_cache(product)
ret = {}
for compdict in proddict["components"]:
ret[compdict["name"]] = compdict
return ret
def getcomponentdetails(self, product, component, force_refresh=False):
"""
Helper for accessing a single component's info. This is a wrapper
around getcomponentsdetails, see that for explanation
"""
d = self.getcomponentsdetails(product, force_refresh)
return d[component]
def getcomponents(self, product, force_refresh=False):
"""
Return a list of component names for the passed product.
This can be implemented with Product.get, but behind the
scenes it uses Bug.legal_values. Reason being that on bugzilla
instances with tons of components, like bugzilla.redhat.com
Product=Fedora for example, there's a 10x speed difference
even with properly limited Product.get calls.
On first invocation the value is cached, and subsequent calls
will return the cached data.
:param force_refresh: Force refreshing the cache, and return
the new data
"""
proddict = self._lookup_product_in_cache(product)
product_id = proddict.get("id", None)
if (force_refresh or
product_id is None or
product_id not in self._cache.component_names):
self.refresh_products(names=[product],
include_fields=["names", "id"])
proddict = self._lookup_product_in_cache(product)
product_id = proddict["id"]
opts = {'product_id': product_id, 'field': 'component'}
names = self._proxy.Bug.legal_values(opts)["values"]
self._cache.component_names[product_id] = names
return self._cache.component_names[product_id]
############################
# component adding/editing #
############################
def _component_data_convert(self, data, update=False):
# Back compat for the old RH interface
convert_fields = [
("initialowner", "default_assignee"),
("initialqacontact", "default_qa_contact"),
("initialcclist", "default_cc"),
]
for old, new in convert_fields:
if old in data:
data[new] = data.pop(old)
if update:
names = {"product": data.pop("product"),
"component": data.pop("component")}
updates = {}
for k in list(data.keys()):
updates[k] = data.pop(k)
data["names"] = [names]
data["updates"] = updates
def addcomponent(self, data):
"""
A method to create a component in Bugzilla. Takes a dict, with the
following elements:
product: The product to create the component in
component: The name of the component to create
desription: A one sentence summary of the component
default_assignee: The bugzilla login (email address) of the initial
owner of the component
default_qa_contact (optional): The bugzilla login of the
initial QA contact
default_cc: (optional) The initial list of users to be CC'ed on
new bugs for the component.
is_active: (optional) If False, the component is hidden from
the component list when filing new bugs.
"""
data = data.copy()
self._component_data_convert(data)
return self._proxy.Component.create(data)
def editcomponent(self, data):
"""
A method to edit a component in Bugzilla. Takes a dict, with
mandatory elements of product. component, and initialowner.
All other elements are optional and use the same names as the
addcomponent() method.
"""
data = data.copy()
self._component_data_convert(data, update=True)
return self._proxy.Component.update(data)
###################
# getbug* methods #
###################
def _process_include_fields(self, include_fields, exclude_fields,
extra_fields):
"""
Internal helper to process include_fields lists
"""
def _convert_fields(_in):
if not _in:
return _in
for newname, oldname in self._get_api_aliases():
if oldname in _in:
_in.remove(oldname)
if newname not in _in:
_in.append(newname)
return _in
ret = {}
if self._check_version(4, 0):
if include_fields:
include_fields = _convert_fields(include_fields)
if "id" not in include_fields:
include_fields.append("id")
ret["include_fields"] = include_fields
if exclude_fields:
exclude_fields = _convert_fields(exclude_fields)
ret["exclude_fields"] = exclude_fields
if self._supports_getbug_extra_fields:
if extra_fields:
ret["extra_fields"] = _convert_fields(extra_fields)
return ret
def _get_bug_autorefresh(self):
"""
This value is passed to Bug.autorefresh for all fetched bugs.
If True, and an uncached attribute is requested from a Bug,
the Bug will update its contents and try again.
"""
return self._bug_autorefresh
def _set_bug_autorefresh(self, val):
self._bug_autorefresh = bool(val)
bug_autorefresh = property(_get_bug_autorefresh, _set_bug_autorefresh)
# getbug_extra_fields: Extra fields that need to be explicitly
# requested from Bug.get in order for the data to be returned.
#
# As of Dec 2012 it seems like only RH bugzilla actually has behavior