aboutsummaryrefslogtreecommitdiff
path: root/monthly-report.py
blob: 5fd794df8c388ae2a9e38a1cc29882bdce5a21c8 (plain)
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
#!/usr/bin/env python
# Copyright (C) 2014 Linaro
#
# Author: Alan Bennett <alan.bennett@linaro.org>
#
# This file, monthly-report.py, is a hack, it's not supported
#
# is distributed WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cards.py.  If not, see <http://www.gnu.org/licenses/>.
#


import ConfigParser
import argparse
import logging
import sys
import datetime
import codecs
import locale
import re
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()

from jira.client import JIRA
DEFAULT_LOGGER_NAME = "test.log"
logger = None
__version__ = "2014.01.1"
DEFAULT_LOGGER_NAME = "cards.dbg.log"
teampattern = re.compile('Team-*', re.IGNORECASE)

def connect_jira(logger):
    """Connect to Jira Instance

    """
    Config = ConfigParser.ConfigParser()
    Config.read("settings.cfg")
    jira_server = Config.get('Jira', 'Server')
    jira_user = Config.get('Jira', 'Username')
    jira_pass = Config.get('Jira', 'Password')

    try:
        logger.info("Connection to JIRA %s" % jira_server)
        jira = JIRA(options={'server': jira_server}, basic_auth=(jira_user, jira_pass))
        return jira
    except:
        logger.error("Failed to connect to JIRA")
        return None


def get_logger(name=DEFAULT_LOGGER_NAME, debug=False):
    """
    Retrieves a named logger. Default name is set in the variable
    DEFAULT_LOG_NAME. Debug is set to False by default.

    :param name: The name of the logger.
    :param debug: If debug level should be turned on
    :return: A logger instance.
    """
    logger = logging.getLogger(name)
    ch = logging.StreamHandler()

    if debug:
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        ch.setFormatter(formatter)
        logger.setLevel(logging.DEBUG)
    else:
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter("%(message)s")
        ch.setFormatter(formatter)
        logger.setLevel(logging.INFO)

    logger.addHandler(ch)
    return logger


def setup_args_parser():
    """Setup the argument parsing.

    :return The parsed arguments.
    """
    description = "Walk through the Cards and generate some metrics"
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument("-d", "--debug", action="store_true")
    parser.add_argument("-c", "--component", required=True, help="Jira Component")
    parser.add_argument("-s", "--stale", action="store_true", help="List Cards not updated in > 14 days")
    parser.add_argument("--only_epics", action="store_true", help="List only epics, default is only cards")

    return parser.parse_args()


def get_carddetails(jira, db, issues):
    """get_worklog - Build an intermediate database of recently worked on issues

    :param jira: a database session
    :param db: Dictionary of components
    :param issues: A jira query result

    :return The parsed arguments.
    """
    logger.info(' Number of issues found [' + str(issues.__len__()) + ']')
    for issue in issues:
        logger.debug(issue.key + ' [' + issue.fields.summary + ']')

        team = ""
	if issue.fields.labels.__len__() > 0:
             logger.debug(', '.join(issue.fields.labels))
             for t in issue.fields.labels:
                 m = teampattern.match(t)
                 if m:
                     team = t[5:]
         
        #iterate through each issue and add it to the database
        db.append({'key': issue.key,
                   'assignee': issue.fields.assignee.name if issue.fields.assignee is not None else "Unassigned",
                   'summary': issue.fields.summary,
                   'fixversion': issue.fields.fixVersions[0].name if issue.fields.fixVersions.__len__() > 0 else "" ,
                   'labels': ', '.join(issue.fields.labels) if issue.fields.labels.__len__() > 0 else "" ,
                   'confidence': issue.fields.customfield_11200,
                   'status': issue.fields.status.name,
                   'rank': issue.fields.customfield_10900,
                   'engineeringprogress': issue.renderedFields.customfield_10204,
                   'team' : team})


def stripspecial(incoming):
    if incoming is not None:
        return incoming.replace(u"\u2018", "'").\
            replace(u"\u2019", "'").\
            replace(u"\u201c", '"').\
            replace(u"\u2033", '"').\
            replace(u"\u2013", '"').\
            replace(u"\u2014", '')
    else:
        return ""


def linkit(incoming):
    return '<a href="http://cards.linaro.org/browse/' + incoming + '">' + incoming + '</a>'


def constructquery(args):
    basequery = ' project = card AND component = ' + args.component
    if args.only_epics:
        basequery += ' AND summary ~ epic'
    else:
        basequery += ' AND summary !~ epic '

    if args.stale==True:
        basequery += ' AND updated < -14d '
        basequery += ' AND status != Closed'
    else:
        basequery += ' AND updatedDate > -25d '

    basequery += ' AND level not in ("Private - reporter only")'
    basequery += ' ORDER BY rank'
    return basequery


def report(jira, db, issues, outfile):
    """report - Report by user the amount of time logged (percentage)
    """
    db_sorted = sorted(db, key=lambda field: (field['team'], field['rank']))
    old_assignee = ""
    old_parent = ""
    print >>outfile, '<table border=0>'
    for issue in db_sorted:
        print >>outfile, '<tr><td>&nbsp;&nbsp;</td><td><b>' + linkit(issue['key']) + ' - ' + issue['summary'] + '</b><br>'
        print >>outfile, 'Team: ' + issue['team'] + '<br>'
        print >>outfile, 'Status: ' + issue['status']
        print >>outfile, ', Target Delivery: ' + issue['fixversion']
        if issue['confidence'] is None:
            print >> outfile, ', Confidence: ' + 'Not set'
        else:
            print >>outfile, ', Confidence: ' + issue['confidence'] + '<br>'
        print >>outfile, '' + stripspecial(issue['engineeringprogress']) + '</td></tr>'
    print >>outfile, '</table>'


def walkcards():
    Config = ConfigParser.ConfigParser()
    Config.read("settings.cfg")

    args = setup_args_parser()

    global logger
    logger = get_logger(debug=args.debug)

    jira = connect_jira(logger)

    if jira is None:
        sys.exit(1)

    if args.component is None:
        raise JiraComponentError('You need to specify a jira component')

    # Initialize dictionaries that will be used to store cards
    db = []
    basequery = constructquery(args)
    debugquery = ""

    logger.debug('[' + basequery + ']')
    if debugquery:
        logger.info('WARNING DEBUG ON [' + debugquery + ']')
    issues = jira.search_issues(basequery + debugquery, expand='renderedFields')
    if len(issues) > 0:
        get_carddetails(jira, db, issues)

        week = str(datetime.datetime.now().isocalendar()[1])
        year = str(datetime.datetime.now().isocalendar()[0])
        filename = 'MonthlyReport-' + args.component + '_week-' + year + '_' + week + '.html'
        logger.info('Report saved in [' + filename + ']')

        outfile = open(filename, 'w')
        report(jira, db, issues, outfile)
        outfile.close()


if __name__ == '__main__':
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
    walkcards()