-
Notifications
You must be signed in to change notification settings - Fork 664
/
jira.py
5366 lines (4868 loc) · 205 KB
/
jira.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
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
# coding=utf-8
import logging
import re
import os
from warnings import warn
from deprecated import deprecated
from requests import HTTPError
from .errors import ApiNotFoundError, ApiPermissionError
from .rest_client import AtlassianRestAPI
log = logging.getLogger(__name__)
class Jira(AtlassianRestAPI):
"""
Provide permission information for the current user.
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2
"""
def __init__(self, url, *args, **kwargs):
if "api_version" not in kwargs:
kwargs["api_version"] = "2"
super(Jira, self).__init__(url, *args, **kwargs)
def _get_paged(
self,
url,
params=None,
data=None,
flags=None,
trailing=None,
absolute=False,
):
"""
Used to get the paged data
:param url: string: The url to retrieve
:param params: dict (default is None): The parameter's
:param data: dict (default is None): The data
:param flags: string[] (default is None): The flags
:param trailing: bool (default is None): If True, a trailing slash is added to the url
:param absolute: bool (default is False): If True, the url is used absolute and not relative to the root
:return: A generator object for the data elements
"""
if self.cloud:
if params is None:
params = {}
while True:
response = super(Jira, self).get(
url,
trailing=trailing,
params=params,
data=data,
flags=flags,
absolute=absolute,
)
values = response.get("values", [])
for value in values:
yield value
if response.get("isLast", False) or len(values) == 0:
break
url = response.get("nextPage")
if url is None:
break
# From now on we have absolute URLs with parameters
absolute = True
# Params are now provided by the url
params = {}
# Trailing should not be added as it is already part of the url
trailing = False
else:
raise ValueError("``_get_paged`` method is only available for Jira Cloud platform")
return
def get_permissions(
self,
permissions,
project_id=None,
project_key=None,
issue_id=None,
issue_key=None,
):
"""
Returns a list of permissions indicating which permissions the user has. Details of the user's permissions can
be obtained in a global, project, issue or comment context.
The user is reported as having a project permission:
- in the global context, if the user has the project permission in any project.
- for a project, where the project permission is determined using issue data, if the user meets the
permission's criteria for any issue in the project. Otherwise, if the user has the project permission in
the project.
- for an issue, where a project permission is determined using issue data, if the user has the permission in the
issue. Otherwise, if the user has the project permission in the project containing the issue.
- for a comment, where the user has both the permission to browse the comment and the project permission for the
comment's parent issue. Only the BROWSE_PROJECTS permission is supported. If a commentId is provided whose
permissions does not equal BROWSE_PROJECTS, a 400 error will be returned.
This means that users may be shown as having an issue permission (such as EDIT_ISSUES) in the global context or
a project context but may not have the permission for any or all issues. For example, if Reporters have the
EDIT_ISSUES permission a user would be shown as having this permission in the global context or the context of
a project, because any user can be a reporter. However, if they are not the user who reported the issue queried
they would not have EDIT_ISSUES permission for that issue.
Global permissions are unaffected by context.
This operation can be accessed anonymously.
:param permissions: (str) A list of permission keys. This parameter accepts a comma-separated list. (Required)
:param project_id: (str) id of project to scope returned permissions for.
:param project_key: (str) key of project to scope returned permissions for.
:param issue_id: (str) key of the issue to scope returned permissions for.
:param issue_key: (str) id of the issue to scope returned permissions for.
:return:
"""
url = self.resource_url("mypermissions")
params = {"permissions": permissions}
if project_id:
params["projectId"] = project_id
if project_key:
params["projectKey"] = project_key
if issue_id:
params["issueId"] = issue_id
if issue_key:
params["issueKey"] = issue_key
return self.get(url, params=params)
def get_all_permissions(self):
"""
Returns all permissions that are present in the Jira instance -
Global, Project and the global ones added by plugins
:return: All permissions
"""
url = self.resource_url("permissions")
return self.get(url)
"""
Application properties
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/application-properties
"""
def get_property(self, key=None, permission_level=None, key_filter=None):
"""
Returns an application property
:param key: str
:param permission_level: str
:param key_filter: str
:return: list or item
"""
url = self.resource_url("application-properties")
params = {}
if key:
params["key"] = key
if permission_level:
params["permissionLevel"] = permission_level
if key_filter:
params["keyFilter"] = key_filter
return self.get(url, params=params)
def set_property(self, property_id, value):
"""
Modify an application property via PUT. The "value" field present in the PUT will override the existing value.
:param property_id:
:param value:
:return:
"""
base_url = self.resource_url("application-properties")
url = "{base_url}/{property_id}".format(base_url=base_url, property_id=property_id)
data = {"id": property_id, "value": value}
return self.put(url, data=data)
def get_advanced_settings(self):
"""
Returns the properties that are displayed on the "General Configuration > Advanced Settings" page.
:return:
"""
url = self.resource_url("application-properties/advanced-settings")
return self.get(url)
"""
Application roles. Provides REST access to JIRA's Application Roles.
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/applicationrole
"""
def get_all_application_roles(self):
"""
Returns all ApplicationRoles in the system
:return:
"""
url = self.resource_url("applicationrole")
return self.get(url) or {}
def get_application_role(self, role_key):
"""
Returns the ApplicationRole with passed key if it exists
:param role_key: str
:return:
"""
base_url = self.resource_url("applicationrole")
url = "{base_url}/{role_key}".format(base_url=base_url, role_key=role_key)
return self.get(url) or {}
"""
Attachments
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/attachment
"""
def get_attachments_ids_from_issue(self, issue):
"""
Get attachments IDs from jira issue
:param jira issue key: str
:return: list of integers attachment IDs
"""
issue_id = self.get_issue(issue)["fields"]["attachment"]
list_attachments_id = []
for attachment in issue_id:
list_attachments_id.append({"filename": attachment["filename"], "attachment_id": attachment["id"]})
return list_attachments_id
def get_attachment(self, attachment_id):
"""
Returns the meta-data for an attachment, including the URI of the actual attached file
:param attachment_id: int
:return:
"""
base_url = self.resource_url("attachment")
url = "{base_url}/{attachment_id}".format(base_url=base_url, attachment_id=attachment_id)
return self.get(url)
def download_attachments_from_issue(self, issue, path=None, cloud=True):
"""
Downloads all attachments from a Jira issue.
:param issue: The issue-key of the Jira issue
:param path: Path to directory where attachments will be saved. If None, current working directory will be used.
:param cloud: Use True for Jira Cloud, false when using Jira Data Center or Server
:return: A message indicating the result of the download operation.
"""
try:
if path is None:
path = os.getcwd()
issue_id = self.issue(issue, fields="id")["id"]
if cloud:
url = self.url + "/secure/issueAttachments/%s.zip" % (issue_id)
else:
url = self.url + "/secure/attachmentzip/%s.zip" % (issue_id)
response = self._session.get(url)
attachment_name = "%s_attachments.zip" % (issue_id)
file_path = os.path.join(path, attachment_name)
# if Jira issue doesn't have any attachments _session.get request response will return 22 bytes of PKzip format
file_size = sum(len(chunk) for chunk in response.iter_content(8196))
if file_size == 22:
return "No attachments found on the Jira issue"
if os.path.isfile(file_path):
return "File already exists"
with open(file_path, "wb") as f:
f.write(response.content)
return "Attachments downloaded successfully"
except FileNotFoundError:
raise FileNotFoundError("Verify if directory path is correct and/or if directory exists")
except PermissionError:
raise PermissionError(
"Directory found, but there is a problem with saving file to this directory. Check directory permissions"
)
except Exception as e:
raise e
def get_attachment_content(self, attachment_id):
"""
Returns the content for an attachment
:param attachment_id: int
:return: content as bytes
"""
base_url = self.resource_url("attachment")
url = "{base_url}/content/{attachment_id}".format(base_url=base_url, attachment_id=attachment_id)
return self.get(url, not_json_response=True)
def remove_attachment(self, attachment_id):
"""
Remove an attachment from an issue
:param attachment_id: int
:return: if success, return None
"""
base_url = self.resource_url("attachment")
url = "{base_url}/{attachment_id}".format(base_url=base_url, attachment_id=attachment_id)
return self.delete(url)
def get_attachment_meta(self):
"""
Returns the meta information for an attachments,
specifically if they are enabled and the maximum upload size allowed
:return:
"""
url = self.resource_url("attachment/meta")
return self.get(url)
def get_attachment_expand_human(self, attachment_id):
"""
Returns the information for an expandable attachment in human-readable format
:param attachment_id: int
:return:
"""
base_url = self.resource_url("attachment")
url = "{base_url}/{attachment_id}/expand/human".format(base_url=base_url, attachment_id=attachment_id)
return self.get(url)
def get_attachment_expand_raw(self, attachment_id):
"""
Returns the information for an expandable attachment in raw format
:param attachment_id: int
:return:
"""
base_url = self.resource_url("attachment")
url = "{base_url}/{attachment_id}/expand/raw".format(base_url=base_url, attachment_id=attachment_id)
return self.get(url)
"""
Audit Records. Resource representing the auditing records
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/auditing
"""
def get_audit_records(
self,
offset=None,
limit=None,
filter=None,
from_date=None,
to_date=None,
):
"""
Returns auditing records filtered using provided parameters
:param offset: the number of record from which search starts
:param limit: maximum number of returned results (if is limit is <= 0 or > 1000,
it will be set do default value: 1000)
:param str filter: text query; each record that will be returned must contain
the provided text in one of its fields.
:param str from_date: timestamp in the past; 'from' must be less or equal 'to',
otherwise the result set will be empty only records that where created in the same moment or after
the 'from' timestamp will be provided in response
:param str to_date: timestamp in the past; 'from' must be less or equal 'to',
otherwise the result set will be empty only records that where created in the same moment or earlier than
the 'to' timestamp will be provided in response
:return:
"""
params = {}
if offset:
params["offset"] = offset
if limit:
params["limit"] = limit
if filter:
params["filter"] = filter
if from_date:
params["from"] = from_date
if to_date:
params["to"] = to_date
url = self.resource_url("auditing/record")
return self.get(url, params=params) or {}
def post_audit_record(self, audit_record):
"""
Store a record in Audit Log
:param audit_record: json with compat https://docs.atlassian.com/jira/REST/schema/audit-record#
:return:
"""
url = self.resource_url("auditing/record")
return self.post(url, data=audit_record)
"""
Avatar
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/avatar
"""
def get_all_system_avatars(self, avatar_type="user"):
"""
Returns all system avatars of the given type.
:param avatar_type:
:return: Returns a map containing a list of system avatars.
A map is returned to be consistent with the shape of the project/KEY/avatars REST end point.
"""
base_url = self.resource_url("avatar")
url = "{base_url}/{type}/system".format(base_url=base_url, type=avatar_type)
return self.get(url)
"""
Cluster. (Available for DC) It gives possibility to manage old node in cluster.
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/cluster
"""
def get_cluster_all_nodes(self):
url = self.resource_url("cluster/nodes")
return self.get(url)
def delete_cluster_node(self, node_id):
"""
Delete the node from the cluster if state of node is OFFLINE
:param node_id: str
:return:
"""
base_url = self.resource_url("cluster/node")
url = "{base_url}/{node_id}".format(base_url=base_url, node_id=node_id)
return self.delete(url)
def set_node_to_offline(self, node_id):
"""
Change the node's state to offline if the node is reporting as active, but is not alive
:param node_id: str
:return:
"""
base_url = self.resource_url("cluster/node")
url = "{base_url}/{node_id}/offline".format(base_url=base_url, node_id=node_id)
return self.put(url)
def get_cluster_alive_nodes(self):
"""
Get cluster nodes where alive = True
:return: list of node dicts
"""
return [_ for _ in self.get_cluster_all_nodes() if _["alive"]]
def request_current_index_from_node(self, node_id):
"""
Request current index from node (the request is processed asynchronously)
:return:
"""
base_url = self.resource_url("cluster/index-snapshot")
url = "{base_url}/{node_id}".format(base_url=base_url, node_id=node_id)
return self.put(url)
"""
Troubleshooting. (Available for DC) It gives the posibility to download support zips.
Reference: https://confluence.atlassian.com/support/create-a-support-zip-using-the-rest-api-in-data-center-applications-952054641.html
"""
def generate_support_zip_on_nodes(self, node_ids):
"""
Generate a support zip on targeted nodes of a cluster
:param node_ids: list
:return: dict representing cluster task created
"""
data = {"nodeIds": node_ids}
url = "/rest/troubleshooting/latest/support-zip/cluster"
return self.post(url, data=data)
def check_support_zip_status(self, cluster_task_id):
"""
Check status of support zip creation task
:param cluster_task_id: str
:return:
"""
url = "/rest/troubleshooting/latest/support-zip/status/cluster/{}".format(cluster_task_id)
return self.get(url)
def download_support_zip(self, file_name):
"""
Download created support zip file
:param file_name: str
:return: bytes of zip file
"""
url = "/rest/troubleshooting/latest/support-zip/download/{}".format(file_name)
return self.get(url, advanced_mode=True).content
"""
ZDU (Zero Downtime upgrade) module. (Available for DC)
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/cluster/zdu
"""
def get_cluster_zdu_state(self):
url = self.resource_url("cluster/zdu/state")
return self.get(url)
# Issue Comments
def issue_get_comments(self, issue_id):
"""
Get Comments on an Issue.
:param issue_id: Issue ID
:raises: requests.exceptions.HTTPError
:return:
"""
base_url = self.resource_url("issue")
url = "{base_url}/{issue_id}/comment".format(base_url=base_url, issue_id=issue_id)
return self.get(url)
def issues_get_comments_by_id(self, *args):
"""
Get Comments on Multiple Issues
:param *args: int Issue ID's
:raises: requests.exceptions.HTTPError
:return:
"""
if not all([isinstance(i, int) for i in args]):
raise TypeError("Arguments to `issues_get_comments_by_id` must be int")
data = {"ids": list(args)}
base_url = self.resource_url("comment")
url = "{base_url}/list".format(base_url=base_url)
return self.post(url, data=data)
def issue_get_comment(self, issue_id, comment_id):
"""
Get a single comment
:param issue_id: int or str
:param comment_id: int
:raises: requests.exceptions.HTTPError
:return:
"""
base_url = self.resource_url("issue")
url = "{base_url}/{issue_id}/comment/{comment_id}".format(
base_url=base_url, issue_id=issue_id, comment_id=comment_id
)
return self.get(url)
"""
Comments properties
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/comment/{commentId}/properties
"""
def get_comment_properties_keys(self, comment_id):
"""
Returns the keys of all properties for the comment identified by the key or by the id.
:param comment_id:
:return:
"""
base_url = self.resource_url("comment")
url = "{base_url}/{commentId}/properties".format(base_url=base_url, commentId=comment_id)
return self.get(url)
def get_comment_property(self, comment_id, property_key):
"""
Returns the value a property for a comment
:param comment_id: int
:param property_key: str
:return:
"""
base_url = self.resource_url("comment")
url = "{base_url}/{commentId}/properties/{propertyKey}".format(
base_url=base_url, commentId=comment_id, propertyKey=property_key
)
return self.get(url)
def set_comment_property(self, comment_id, property_key, value_property):
"""
Returns the keys of all properties for the comment identified by the key or by the id.
:param comment_id: int
:param property_key: str
:param value_property: object
:return:
"""
base_url = self.resource_url("comment")
url = "{base_url}/{commentId}/properties/{propertyKey}".format(
base_url=base_url, commentId=comment_id, propertyKey=property_key
)
data = {"value": value_property}
return self.put(url, data=data)
def delete_comment_property(self, comment_id, property_key):
"""
Deletes a property for a comment
:param comment_id: int
:param property_key: str
:return:
"""
base_url = self.resource_url("comment")
url = "{base_url}/{commentId}/properties/{propertyKey}".format(
base_url=base_url, commentId=comment_id, propertyKey=property_key
)
return self.delete(url)
"""
Component
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/component
"""
def component(self, component_id):
base_url = self.resource_url("component")
return self.get("{base_url}/{component_id}".format(base_url=base_url, component_id=component_id))
def get_component_related_issues(self, component_id):
"""
Returns counts of issues related to this component.
:param component_id:
:return:
"""
base_url = self.resource_url("component")
url = "{base_url}/{component_id}/relatedIssueCounts".format(base_url=base_url, component_id=component_id)
return self.get(url)
def create_component(self, component):
log.info('Creating component "%s"', component["name"])
base_url = self.resource_url("component")
url = "{base_url}/".format(base_url=base_url)
return self.post(url, data=component)
def update_component(self, component, component_id):
base_url = self.resource_url("component")
url = "{base_url}/{component_id}".format(base_url=base_url, component_id=component_id)
return self.put(url, data=component)
def delete_component(self, component_id):
log.info('Deleting component "%s"', component_id)
base_url = self.resource_url("component")
return self.delete("{base_url}/{component_id}".format(base_url=base_url, component_id=component_id))
def update_component_lead(self, component_id, lead):
data = {"id": component_id, "leadUserName": lead}
base_url = self.resource_url("component")
return self.put(
"{base_url}/{component_id}".format(base_url=base_url, component_id=component_id),
data=data,
)
"""
Configurations of Jira
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/configuration
"""
def get_configurations_of_jira(self):
"""
Returns the information if the optional features in JIRA are enabled or disabled.
If the time tracking is enabled, it also returns the detailed information about time tracking configuration.
:return:
"""
url = self.resource_url("configuration")
return self.get(url)
"""
Custom Field
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/customFieldOption
https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/customFields
https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/field
"""
def get_custom_field_option(self, option_id):
"""
Returns a full representation of the Custom Field Option that has the given id.
:param option_id:
:return:
"""
base_url = self.resource_url("customFieldOption")
url = "{base_url}/{id}".format(base_url=base_url, id=option_id)
return self.get(url)
def get_custom_fields(self, search=None, start=1, limit=50):
"""
Get custom fields. Evaluated on 7.12
:param search: str
:param start: long Default: 1
:param limit: int Default: 50
:return:
"""
url = self.resource_url("customFields")
params = {}
if search:
params["search"] = search
if start:
params["startAt"] = start
if limit:
params["maxResults"] = limit
return self.get(url, params=params)
def get_all_fields(self):
"""
Returns a list of all fields, both System and Custom
:return: application/jsonContains a full representation of all visible fields in JSON.
"""
url = self.resource_url("field")
return self.get(url)
def create_custom_field(self, name, type, search_key=None, description=None):
"""
Creates a custom field with the given name and type
:param name: str - name of the custom field
:param type: str, like 'com.atlassian.jira.plugin.system.customfieldtypes:textfield'
:param search_key: str, like above
:param description: str
"""
url = self.resource_url("field")
data = {"name": name, "type": type}
if search_key:
data["search_key"] = search_key
if description:
data["description"] = description
return self.post(url, data=data)
def get_custom_field_option_context(self, field_id, context_id):
"""
Gets the current values of a custom field
:param field_id:
:param context_id:
:return:
Reference: https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-issue-custom-field-options/#api-rest-api-2-field-fieldid-context-contextid-option-get
"""
url = self.resource_url(
"field/{field_id}/context/{context_id}/option".format(field_id=field_id, context_id=context_id),
api_version=2,
)
return self.get(url)
def add_custom_field_option(self, field_id, context_id, options):
"""
Adds the values given to the custom field
Administrator permission required
:param field_id:
:param context_id:
:param options: List of values to be added
:return:
Reference: https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-issue-custom-field-options/#api-rest-api-2-field-fieldid-context-contextid-option-post
"""
data = {"options": []}
for i in options:
data["options"].append({"disabled": "false", "value": i})
url = self.resource_url(
"field/{field_id}/context/{context_id}/option".format(field_id=field_id, context_id=context_id),
api_version=2,
)
return self.post(url, data=data)
"""
Dashboards
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/dashboard
"""
def get_dashboards(self, filter="", start=0, limit=10):
"""
Returns a list of all dashboards, optionally filtering them.
:param filter: OPTIONAL: an optional filter that is applied to the list of dashboards.
Valid values include "favourite" for returning only favourite dashboards,
and "my" for returning dashboards that are owned by the calling user.
:param start: the index of the first dashboard to return (0-based). must be 0 or a multiple of maxResults
:param limit: a hint as to the maximum number of dashboards to return in each call.
Note that the JIRA server reserves the right to impose a maxResults limit that is lower
than the value that a client provides, dues to lack or resources or any other condition.
When this happens, your results will be truncated.
Callers should always check the returned maxResults to determine
the value that is effectively being used.
:return:
"""
params = {}
if filter:
params["filter"] = filter
if start:
params["startAt"] = start
if limit:
params["maxResults"] = limit
url = self.resource_url("dashboard")
return self.get(url, params=params)
def get_dashboard(self, dashboard_id):
"""
Returns a single dashboard
:param dashboard_id: Dashboard ID Int
:return:
"""
url = self.resource_url("dashboard/{dashboard_id}".format(dashboard_id=dashboard_id))
return self.get(url)
"""
Filters. Resource for searches
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/filter
"""
def create_filter(self, name, jql, description=None, favourite=False):
"""
:param name: str
:param jql: str
:param description: str, Optional. Empty string by default
:param favourite: bool, Optional. False by default
"""
data = {
"jql": jql,
"name": name,
"description": description if description else "",
"favourite": "true" if favourite else "false",
}
url = self.resource_url("filter")
return self.post(url, data=data)
def edit_filter(self, filter_id, name, jql=None, description=None, favourite=None):
"""
Updates an existing filter.
:param filter_id: Filter ID
:param name: Filter Name
:param jql: Filter JQL
:param description: Filter description
:param favourite: Indicates if filter is selected as favorite
:return: Returns updated filter information
"""
data = {"name": name}
if jql:
data["jql"] = jql
if description:
data["description"] = description
if favourite:
data["favourite"] = favourite
base_url = self.resource_url("filter")
url = "{base_url}/{id}".format(base_url=base_url, id=filter_id)
return self.put(url, data=data)
def get_filter(self, filter_id):
"""
Returns a full representation of a filter that has the given id.
:param filter_id:
:return:
"""
base_url = self.resource_url("filter")
url = "{base_url}/{id}".format(base_url=base_url, id=filter_id)
return self.get(url)
def update_filter(self, filter_id, jql, **kwargs):
"""
:param filter_id: int
:param jql: str
:param kwargs: dict, Optional (name, description, favourite)
:return:
"""
allowed_fields = ("name", "description", "favourite")
data = {"jql": jql}
for k, v in kwargs.items():
if k in allowed_fields:
data.update({k: v})
base_url = self.resource_url("filter")
url = "{base_url}/{id}".format(base_url=base_url, id=filter_id)
return self.put(url, data=data)
def delete_filter(self, filter_id):
"""
Deletes a filter that has the given id.
:param filter_id:
:return:
"""
base_url = self.resource_url("filter")
url = "{base_url}/{id}".format(base_url=base_url, id=filter_id)
return self.delete(url)
def get_filter_share_permissions(self, filter_id):
"""
Gets share permissions of a filter.
:param filter_id: Filter ID
:return: Returns current share permissions of filter
"""
base_url = self.resource_url("filter")
url = "{base_url}/{id}/permission".format(base_url=base_url, id=filter_id)
return self.get(url)
def add_filter_share_permission(
self,
filter_id,
type,
project_id=None,
project_role_id=None,
groupname=None,
user_key=None,
view=None,
edit=None,
):
"""
Adds share permission for a filter. See the documentation of the sharePermissions.
:param filter_id: Filter ID
:param type: What type of permission is granted (i.e. user, project)
:param project_id: Project ID, relevant for type 'project' and 'projectRole'
:param project_role_id: Project role ID, relevant for type 'projectRole'
:param groupname: Group name, relevant for type 'group'
:param user_key: User key, relevant for type 'user'
:param view: Sets view permission
:param edit: Sets edit permission
:return: Returns updated share permissions
"""
base_url = self.resource_url("filter")
url = "{base_url}/{id}/permission".format(base_url=base_url, id=filter_id)
data = {"type": type}
if project_id:
data["projectId"] = project_id
if project_role_id:
data["projectRoleId"] = project_role_id
if groupname:
data["groupname"] = groupname
if user_key:
data["userKey"] = user_key
if view:
data["view"] = view
if edit:
data["edit"] = edit
return self.post(url, data=data)
def delete_filter_share_permission(self, filter_id, permission_id):
"""
Removes share permission
:param filter_id: Filter ID
:param permission_id: Permission ID to be removed
:return:
"""
base_url = self.resource_url("filter")
url = "{base_url}/{id}/permission/{permission_id}".format(
base_url=base_url, id=filter_id, permission_id=permission_id
)
return self.delete(url)
"""
Group.
Reference: https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/group
https://docs.atlassian.com/software/jira/docs/api/REST/8.5.0/#api/2/groups
"""
def get_groups(self, query=None, exclude=None, limit=20):
"""
REST endpoint for searching groups in a group picker
Returns groups with substrings matching a given query. This is mainly for use with the group picker,
so the returned groups contain html to be used as picker suggestions. The groups are also wrapped
in a single response object that also contains a header for use in the picker,
specifically Showing X of Y matching groups.
The number of groups returned is limited by the system property "jira.ajax.autocomplete.limit"
The groups will be unique and sorted.
:param query: str - Query of searching groups by name.
:param exclude: str - Exclude groups from search results.
:param limit: int
:return: Returned even if no groups match the given substring
"""
url = self.resource_url("groups/picker")
params = {}
if query:
params["query"] = query
else:
params["query"] = ""
if exclude:
params["exclude"] = exclude
if limit:
params["maxResults"] = limit
return self.get(url, params=params)
def create_group(self, name):
"""
Create a group by given group parameter
:param name: str
:return: New group params
"""
url = self.resource_url("group")
data = {"name": name}
return self.post(url, data=data)
def remove_group(self, name, swap_group=None):
"""
Delete a group by given group parameter
If you delete a group and content is restricted to that group, the content will be hidden from all users
To prevent this, use this parameter to specify a different group to transfer the restrictions
(comments and worklogs only) to
:param name: str - name
:param swap_group: str - swap group
:return:
"""
log.info("Removing group: %s ", name)
url = self.resource_url("group")
if swap_group is not None:
params = {"groupname": name, "swapGroup": swap_group}
else:
params = {"groupname": name}
return self.delete(url, params=params)
def get_all_users_from_group(self, group, include_inactive_users=False, start=0, limit=50):
"""
Just wrapping method user group members
:param group:
:param include_inactive_users:
:param start: OPTIONAL: The start point of the collection to return. Default: 0.
:param limit: OPTIONAL: The limit of the number of users to return, this may be restricted by
fixed system limits. Default by built-in method: 50
:return:
"""
url = self.resource_url("group/member")
params = {}
if group:
params["groupname"] = group
params["includeInactiveUsers"] = include_inactive_users
params["startAt"] = start
params["maxResults"] = limit
return self.get(url, params=params)
def add_user_to_group(self, username=None, group_name=None, account_id=None):
"""
Add given user to a group
For Jira DC/Server platform