-
Notifications
You must be signed in to change notification settings - Fork 0
/
iJira.py
1754 lines (1390 loc) · 65.4 KB
/
iJira.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 -*-
# Name: iJira.py
# Created by Cody Hughes
# created date: 08/11/2021
# current version: 1
#
# Description:
# This interface is intended to offer access to all data stored within
# Jira. It requires no manual login as it uses a
# preset authentication.
#
#
from jira import JIRA
from ast import literal_eval as le
from datetime import datetime, timedelta
import logging
import pandas as pd
import re
from typing import Optional
# module's logger
_log = logging.getLogger(__name__)
class iJira():
"""Interface for Jira API commands
"""
DATE_FORMAT = "%Y/%m/%d %H:%M"
__cert_file: str
__cert_data: object
__jira: JIRA
__is_logged_in: bool
__issues: list = []
__issue_links: dict = {}
__comments: dict = {}
__components: dict = {}
__labels: dict = {}
__histories: dict = {}
__watchers: dict = {}
__time_in_status: dict = {}
__status_issue_count_time_series: dict
def __init__(self,cert_file_path:str)->None:
"""Initializes interface object with authentication info"""
self.__cert_file = cert_file_path
self.__is_logged_in = False
self.__status_issue_count_time_series = {}
self.__load_interface()
def __load_interface(self)->None:
"""Performs API login from interface initialization"""
try:
# load private key data into var
with open(self.__cert_file, 'r') as key_cert_file:
self.__cert_data = key_cert_file.read()
#print(f'cert file: {self.__cert_data}')
except FileNotFoundError:
# if no file found push error
_log.error(f'No PEM file found in given location: {self.__cert_file}',exc_info=True)
raise FileNotFoundError("No .PEM file found!")
# get auth dict from txt file
oauth = self.__read_in_auth_dict()
# add in cert data file
oauth['key_cert'] = self.__cert_data
try: # to login here, if so set flag __is_logged_in
self.__jira = JIRA('https://maestro-api.dhs.gov/jira',oauth=oauth)
self.__is_logged_in = True
except Exception as e:
#TODO: replace exception with proper faild login exception
_log.error('Failed to login',exc_info=True)
self.__is_logged_in = False
@property
def jira_obj(self):
"""the Jira object is the JIRA python library API object
Returns:
[JIRA]: The underlying JIRA api object
"""
return self.__jira
@property
def is_logged_in(self)->bool:
"""Property to let user know of successful login or not
Returns:
-----
bool: True if login was successful, false otherwise
"""
return self.__is_logged_in
def get_issues(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get issue objects and return as list of issue objects
Parameters:
-----
limit (Optional[int], optional): Number of Issues to return. Default is to return All.
project_key (Optional[str], optional): [description]. Defaults to `'FRD'`.
return_df (bool, optional): If you need a pandas dataframe instead of list of Issue objects set to `True`. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
Defaults to list, but able to return pandas dataframe if needed
"""
# reuse a previous pull of issues if it's not empty
if force_refresh or len(self.__issues) == 0:
_log.info('Refreshing Issues...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
_log.info(f'Issue Count: {limit} issue(s) found.',exc_info=True)
# get issues list of dict
self.__issues = [Jira_Issue(self.__jira,i.key)
for i in self.__jira.search_issues(
f'project = {project_key}',maxResults=limit)]
_log.info(f'{len(self.__issues)} Issues retreived.')
if return_df:
df = pd.DataFrame([i.record for i in self.__issues])
df.insert(0, 'refresh_date', pd.to_datetime('now').replace(microsecond=0))
return df
else:
return self.__issues
def get_issue_links(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get Issue Links and return a list of Issue Links
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All.
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of issue keys with issue link dictionaries of {id:name}
"""
if force_refresh or len(self.__issue_links) == 0:
_log.info('Refreshing Issue Links...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
# get issues
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
# setup empty dict for results
results = {}
#add rownum for indexing
rownum = 0
# temp issue keys
inward_key = ''
outward_key = ''
# loop through all issues and build dict of all components
for issue in issues:
for l in issue.issue_links:
rownum += 1
if l.inward_issue:
inward_key = l.inward_issue
if l.outward_issue:
outward_key = l.outward_issue
results[f'{rownum}']={'issue_key':issue.key,
'link_id':l.link_id,
'link_type':l.link_type,
'link_inward_desc':l.inward_descr,
'link_outward_desc':l.outward_descr,
'inward_issue_key':inward_key,
'outward_issue_key':outward_key,
'refresh_date':pd.to_datetime('now').replace(microsecond=0)}
# set var to hold previous pull of links
self.__issue_links = results
_log.info(f'{len(self.__issue_links)} Issue links retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__issue_links,orient='index')
return df
else:
return self.__issue_links
def get_histories(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get Historic records for all Issues
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All.
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of Historic Records
"""
if force_refresh or len(self.__histories) == 0:
_log.info('Refreshing Histories...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
# get issues
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
# setup empty dict for results
results = {}
#add rownum for indexing
rownum = 0
# loop through all issues and build dict of all components
for issue in issues:
for rec in issue.change_history:
# filter for last 3 months only
#if abs(pd.to_datetime(rec.updated_date)-pd.to_datetime(datetime.now().date())).days <=90:
# set row number for indexing
rownum += 1
# build out dict of each record
results[f'{rownum}']={'issue_key':issue.key,
'updated_by':rec.updated_by,
'date_of_change':rec.updated_date,
'field':rec.field_name,
'new_value':rec.new_value,
'old_value':rec.old_value,
'refresh_date':pd.to_datetime('now').replace(microsecond=0)}
# set var to hold previous pull of links
self.__histories = results
_log.info(f'{len(self.__histories)} Historic Changes retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__histories,orient='index')
return df
else:
return self.__histories
def get_comments(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get Comments and return a dictionary of comments
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All..
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of issue keys with comment dictionaries of {id:name}
"""
if force_refresh or len(self.__comments) == 0:
_log.info('Refreshing Comments...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
# get issues
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
# setup empty dict for results
results = {}
#add rownum for indexing
rownum = 0
# loop through all issues and build dict of all components
for issue in issues:
for c in issue.comments:
rownum += 1
results[f'{rownum}']={'issue_key':issue.key,
'comment_id':c.id,
'comment_body':c.body,
'refresh_date':pd.to_datetime('now').replace(microsecond=0)}
# set var to hold commments
self.__comments = results
_log.info(f'{len(self.__comments)} Comments retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__comments,orient='index')
return df
else:
return self.__comments
def get_components(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get Components and return a dictionary of components
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All.
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of issue keys with component dictionaries of {id:name}
"""
if force_refresh or len(self.__components) == 0:
_log.info('Refreshing Components...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
# get issues
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
# setup empty dict for results
results = {}
#add row num for indexing
rownum = 0
# loop through all issues and build dict of all components
for issue in issues:
for c in issue.components:
rownum += 1
results[f'{rownum}']={'issue_key':issue.key,
'component_id': c.id,
'component_name':c.name,
'refresh_date':pd.to_datetime('now').replace(microsecond=0)}
# set var for component storage
self.__components = results
_log.info(f'{len(self.__components)} Components retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__components,orient='index')
return df
else:
return self.__components
def get_labels(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get Labels and return a dictionary of labels
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All.
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of issue keys with label dictionaries of {id:name}
"""
if force_refresh or len(self.__labels) == 0:
_log.info('Refreshing Labels...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
# get issues
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
# setup empty dict for results
results = {}
#add row num for indexing
rownum = 0
# loop through all issues and build dict of all components
for issue in issues:
for l in issue.labels:
rownum += 1
results[f'{rownum}']={'issue_key':issue.key,
'label_name':l,
'refresh_date':pd.to_datetime('now').replace(microsecond=0)}
# set var for storage
self.__labels = results
_log.info(f'{len(self.__labels)} Labels retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__labels,orient='index')
return df
else:
return self.__labels
def get_time_in_status(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get the time an issue is in each status and return a dictionary of those results
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All.
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of issue keys with status dictionaries
"""
if force_refresh or len(self.__time_in_status) == 0:
_log.info('Refreshing Time In Status Report...')
if limit is None:
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
results = {}
# row num is used for indexing in the result dictionary
rownum = 0
for issue in issues:
for status,val in issue.time_in_status.items():
rownum += 1
results[f'{rownum}']={'issue_key':issue.key,
'status':status,
'days':val['days'],
'hours':val['hours'],
'minutes':val['minutes']}
# save to global var for reuse
self.__time_in_status = results
_log.info(f'{len(self.__time_in_status)} time in status records retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__time_in_status,orient='index')
return df
else:
return self.__time_in_status
def get_watchers(self,limit:Optional[int]=None,project_key:Optional[str]='FRD',return_df:bool=False,force_refresh:bool=False):
"""Get Watchers and return a dictionary of watchers
Parameters:
-----
limit (Optional[int], optional): Number of issues to return can be limited. Default is to return All.
project_key (Optional[str], optional): Specifiy a Project Key to pull issues from. Defaults to `'FRD'`.
return_df (bool, optional): Option to return as Pandas Dataframe instead of dict. Defaults to `False`.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
dict: By default it returns a dictionary of issue keys with watcher dictionaries of {id:name}
"""
if force_refresh or len(self.__watchers) == 0:
_log.info('Refreshing Watchers...')
# check for limit
if limit is None:
# get total issue count
limit = int(self.__jira.search_issues(
f'project = {project_key}',
maxResults=1,startAt=0,json_result=True)['total'])
# get issues
issues = self.get_issues(limit=limit,project_key=project_key,force_refresh=force_refresh)
# setup empty dict for results
results = {}
#add row num for indexing
rownum = 0
# loop through all issues and build dict of all components
for issue in issues:
for w in issue.watchers:
rownum +=1
results[f'{rownum}']={'issue_key':issue.key,
'watcher_key':w.key,
'watcher_name':w.name,
'watcher_email':w.emailAddress,
'watcher_display_name':w.displayName,
'watcher_active':w.active,
'refresh_date':pd.to_datetime('now').replace(microsecond=0)}
self.__watchers = results
_log.info(f'{len(self.__watchers)} Watchers retrieved')
# determine how to return results; either dataframe | dict
if return_df:
df = pd.DataFrame.from_dict(self.__watchers,orient='index')
return df
else:
return self.__watchers
def export_issues_report(self,f_name:str='Issues',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves issues report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'Issues'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of records to return, if none returns all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the issues have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_issues(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc,index=False)
return save_loc
def export_issue_links_report(self,f_name:str='IssueLinks',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves issue links report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'IssueLinks'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the issue links have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_issue_links(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
def export_change_history_report(self,f_name:str='ChangeHistory',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves historic report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'IssueLinks'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the issue links have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_histories(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
def export_comments_report(self,f_name:str='Comments',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves components report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'Comments'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the Comments have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_comments(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
def export_components_report(self,f_name:str='Components',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves components report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'Components'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the Components have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_components(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
def export_label_report(self,f_name:str='Labels',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves labels report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'Labels'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the Labels have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_labels(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
def export_issue_count_time_series_report(self,f_name:str='IssueCountTimeSeries',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""[summary]
PARAMETERS
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'IssueCountTimeSeries'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the issue counts have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
_log.info('Refreshing Issue Count by Status Report...')
issues = self.get_issues(limit=limit,force_refresh=force_refresh)
status_change_records = [r for hl in [i.change_history for i in issues] for r in hl if r.field_name == 'status']
status_set = {s:0 for s in list(set([str(c.new_value).lower() for c in status_change_records]))}
update_dates = [datetime.strptime(c.updated_date, self.DATE_FORMAT).strftime("%Y/%m/%d") for c in status_change_records]
save_loc = rf'{f_path}\{f_name}.xlsx'
expanded_dates = pd.date_range(start=min(update_dates),end=max(update_dates),freq='D',normalize=True,closed=None)
# preload dictionary in order to update the counts
for d in expanded_dates:
d = d.strftime("%Y/%m/%d")
self.__status_issue_count_time_series[str(d)] = status_set.copy()
for d in expanded_dates:
idx_date = datetime.date(d).strftime("%Y/%m/%d")
_log.debug(f'record - {idx_date} ')
tmp_status = {}
for status in status_set:
total = sum([1 for s in status_change_records
if idx_date >= s.start_date.strftime("%Y/%m/%d")
and idx_date <=s.end_date.strftime("%Y/%m/%d")
and s.new_value.lower() == status])
_log.debug(f'date: {idx_date} | status: "{status}" | ttl: {total}')
tmp_status[status] = total
# after status loop set statuss to date in results dict
self.__status_issue_count_time_series[str(idx_date)] = tmp_status
_log.debug(f'UPDATED RECORD - {idx_date} | {self.__status_issue_count_time_series[str(idx_date)]}')
_log.debug(f'Dict Time series: {self.__status_issue_count_time_series}')
temp_dict = {}
idx = 0
_log.debug(f'Flattening Issue count time series')
for d,s in self.__status_issue_count_time_series.items():
_log.debug(f'Date: {d} | statuses: {s}')
for k,v in s.items():
temp_dict[idx] = {'date':d,'status':k,'total':v,'refresh_date':datetime.now()}
idx +=1
pd.DataFrame.from_dict(temp_dict,orient='index').to_excel(save_loc)
return save_loc
def export_time_in_status_report(self,f_name:str='TimeInStatus',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves time in status report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'TimeInStatus'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the time in status's have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_time_in_status(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
def export_watchers_report(self,f_name:str='Watchers',f_path:str=r'.\data',limit:Optional[int]=None,force_refresh:bool=False)->str:
"""Saves watchers report out to excel xlsx file
Parameters:
-----
f_name (str, optional): File name (NO EXTENSION). Defaults to `'Watchers'`.
f_path (str, optional): File Path . Defaults to r`'.\data'`.
limit (Optional[int], optional): Number of issues to search through, if none searches all found. Default is to return All.
force_refresh (bool, optional): Default is `False` - if the Watchers have already been pulled, dont pull again.
If `True` - run a fresh pull.
Returns:
-----
str: The path to where the file was saved.
"""
save_loc = rf'{f_path}\{f_name}.xlsx'
self.get_watchers(force_refresh=force_refresh,limit=limit,return_df=True).to_excel(save_loc)
return save_loc
@classmethod
def __read_in_auth_dict(cls,path:Optional[str] = r'.\auth\auth_dict.txt')->dict:
"""Reads in a text file in dictionary format
Parameters:
-----
path (Optional[str], optional): Path to auth file. Defaults to `.\\auth\\auth_dict.txt`.
Raises:
-----
FileNotFoundError: if no auth file found in default location and no location provided
Returns:
-----
dict: Dictionary object for use in authentication
"""
try:
f = open(path,'r')
d = {}
d = le(f.read())
except FileNotFoundError as e:
_log.error(f'Could not find Auth File in : {path}',exec_info=True)
raise FileNotFoundError('No Auth file found!')
finally:
return d
class Jira_Issue():
"""Contains all details and functionality for a single issue
"""
DATE_FORMAT = "%Y/%m/%d %H:%M"
__authorized_jira: JIRA
__agg_progress: int
__agg_progress_total: int
__assignee_name: str
__assignee_key: str
__comments: dict
__comments_count: int
__components: dict
__created_dt: str
__creator_key: str
__creator_name: str
__cur_status: str
__epic_key: str
__historic_records: list
__histories: list
__is_subtask:bool
__issue_age_txt: str
__issue_key: str
__issue_links: list
__issue_record: dict
__issue_type: str
__labels: dict
__label_count: int
__latest_comment: str
__latest_comment_dt: str
__open_days: int
__priority_type:str
__priority_descr:str
__progress: int
__project_key: str
__project_name: str
__progress_total: int
__reporter_key: str
__reporter_name: str
__summary: str
__time_in_status: dict
__vote_count: int
__watchers: dict
__watcher_count: int
def __init__(self,pJira: JIRA,pIssue_Key: str)->None:
"""Initilizer for Issue object.
Parameters:
-----
pJira (`JIRA`): The instantiated / authenticated `JIRA` API object
pIssue_Key (str): The Issue Key to load
"""
self.__issue_key = pIssue_Key
self.__authorized_jira = pJira
self.__agg_progress = None
self.__agg_progress_total = None
self.__assignee_name = None
self.__assignee_key = None
self.__comments = {}
self.__comments_count = None
self.__components = {}
self.__created_dt = None
self.__creator_key = None
self.__creator_name = None
self.__cur_status = None
self.__epic_key = None
self.__historic_records = []
self.__histories = []
self.__is_subtask = False
self.__issue_age_txt = None
self.__issue_links = []
self.__issue_record = {}
self.__issue_type = None
self.__labels = {}
self.__label_count = None
self.__latest_comment = None
self.__latest_comment_dt = None
self.__open_days = 0
self.__priority_type = None
self.__priority_descr = None
self.__progress = None
self.__project_key = None
self.__project_name = None
self.__progress_total = None
self.__reporter_key = None
self.__reporter_name = None
self.__summary = None
self.__time_in_status = {}
self.__vote_count = None
self.__watchers = {}
self.__watcher_count = None
self.__load_issue()
def __load_issue(self):
"""initial load up of issue object without lists"""
_log.debug(f'Loading Issue : {self.__issue_key}')
jira = self.__authorized_jira
issue = jira.issue(self.__issue_key,expand='changelog')
try:
self.__watchers = jira.watchers(issue).watchers
except AttributeError:
# Error is thrown when a field is empty.
# Just ignore and move on, as Pandas turns it into None
_log.debug(f'No Watchers for issue: {self.__issue_key}',exc_info=True)
try:
self.__comments = jira.comments(issue)
except AttributeError:
# Error is thrown when a field is empty.
_log.debug(f'No Comments for issue: {self.__issue_key}',exc_info=True)
try:
self.__components = issue.fields.components
except AttributeError:
# Error is thrown when a field is empty.
_log.debug(f'No Components for issue: {self.__issue_key}',exc_info=True)
try:
self.__histories = issue.changelog.histories
#_log.debug(f'issue: {self.key} | history: {self.__histories}')
except AttributeError:
# Error is thrown when a field is empty.
_log.debug(f'No Changelog for issue: {self.__issue_key}',exc_info=True)
try:
_log.debug(f'Getting Issue Links for : {self.key}')
self.__issue_links = [Issue_Link(l) for l in issue.fields.issuelinks]
except AttributeError:
# Error is thrown when a field is empty.
_log.debug(f'No Issue Links for issue: {self.__issue_key}',exc_info=True)
try:
self.__labels = issue.fields.labels
except AttributeError:
# Error is thrown when a field is empty.
_log.debug(f'No Labels for issue: {self.__issue_key}',exc_info=True)
# start building record
self.__issue_record['issue_key'] = self.__issue_key
self.__issue_record['created_date'] = self.__created_dt = datetime.strptime(issue.fields.created,'%Y-%m-%dT%H:%M:%S.%f%z').date()
self.__issue_record['agg_progress'] = self.__agg_progress = issue.fields.aggregateprogress.progress
self.__issue_record['agg_progress_total'] = self.__agg_progress_total = issue.fields.aggregateprogress.total
self.__issue_record['latest_comment'] = self.__latest_comment = self.clean_html(str(issue.fields.customfield_18501))
try:
self.__issue_record['latest_comment_date'] = self.__latest_comment_dt = datetime.strptime(issue.fields.customfield_18502,'%Y-%m-%dT%H:%M:%S.%f%z').date()
except TypeError:
# Error is thrown when a field is empty. So set to None
self.__issue_record['latest_comment_date'] = self.__latest_comment_dt = None
_log.debug(f'No Comments for issue: {self.__issue_key}',exc_info=True)
self.__issue_record['epic_key'] = self.__epic_key = issue.fields.customfield_10801
self.__issue_record['summary'] = self.__summary = issue.fields.summary
self.__issue_record['priority_type'] = self.__priority_type = issue.fields.priority.name
self.__issue_record['project_key'] = self.__project_key = issue.fields.project.key
self.__issue_record['project_name'] = self.__project_name = issue.fields.project.name
self.__issue_record['progress'] = self.__progress = issue.fields.progress.progress
self.__issue_record['progress_total'] = self.__progress_total = issue.fields.progress.total
self.__issue_record['reporter_key'] = self.__reporter_key = issue.fields.reporter.key
self.__issue_record['reporter_name'] = self.__reporter_name = issue.fields.reporter.displayName
self.__issue_record['creator_key'] = self.__creator_key = issue.fields.creator.key
self.__issue_record['creator_name'] = self.__creator_name = issue.fields.creator.displayName
self.__issue_record['current_status'] = self.__cur_status = issue.fields.status.name
self.__issue_record['issue_age_txt'] = self.__issue_age_txt = issue.fields.customfield_22332
try:
self.__issue_record['assignee_key'] = self.__assignee_key = issue.fields.assignee.key
self.__issue_record['assignee_name'] = self.__assignee_name = issue.fields.assignee.displayName
except AttributeError:
# Error is thrown when a field is empty.
_log.debug(f'No Assignee for issue: {self.__issue_key}',exc_info=True)
self.__issue_record['issue_type'] = self.__issue_type = issue.fields.issuetype.name
self.__issue_record['is_subtask'] = self.__is_subtask = issue.fields.issuetype.subtask