summaryrefslogtreecommitdiffstats
path: root/jira2gv
blob: 98dfb101be94b4de0add46836b5bd81e77fbff74 (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
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
#!/usr/bin/env perl
#############################################################################
##
## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
## Contact: http://www.qt-project.org/legal
##
## Script for generating a Graphviz (.gv) file from Jira bugreports.
## Might not work for any other Jira DB than the Qt Project bugreports DB.
##
## $QT_BEGIN_LICENSE:LGPL$
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance with the commercial license agreement provided with the
## Software or, alternatively, in accordance with the terms contained in
## a written agreement between you and Digia.  For licensing terms and
## conditions see http://qt.digia.com/licensing.  For further information
## use the contact form at http://qt.digia.com/contact-us.
##
## GNU Lesser General Public License Usage
## Alternatively, this file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
##
## In addition, as a special exception, Digia gives you certain additional
## rights.  These rights are described in the Digia Qt LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3.0 as published by the Free Software
## Foundation and appearing in the file LICENSE.GPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU General Public License version 3.0 requirements will be
## met: http://www.gnu.org/copyleft/gpl.html.
##
##
## $QT_END_LICENSE$
##
#############################################################################

use strict;
use warnings;

package Qt::Jira2Gv;


=head1 NAME

jira2gv - generates a Graphviz (.gv) file from a Jira issue

=head1 SYNOPSIS

 jira2gv <--server URL> <--issue JiraIssue> [--verbose] [--cache]
         [--edgeExtra JiraIssue=<valule>] [--issueStop JiraIssue]

This script fetches hierarchical Jira items and generates a Graphviz graph.
It will only display outward dependencies (so sub-tasks and "depends on" links) on a task.

=head1 OPTIONS

=over

=item --verbose, -v

Be verbose. Will print a statement for each issue fetched from Jira.

=item --cache, -c

Read or create cached items.  This will make the script store each Jira item fetched, and use it
the next time around you run the script. Very useful for debugging, but don't use it on production
system, as you'll never get updated issues.

=item --server <url-base>

HTTP address of the server to fetch Jira issues from.

=item --issue <JIra issue identifier>

Jira issue identifier of the issue to start the graph from.

=item --edgeExtra <Jira issue identifier>='['<Edge extra data>']'

Adds edge extra data to any edge going to the prefixed Jira issue. Be sure to include the [].

Example: --edgeExtra JIRA-1234=[minlen=2]

=item --issueStop <Jira issue identifier>

Don't generate sub-graph passed this Jira issue.

=back

B<EXAMPLES:>

=over

Generate a graph from the Qt Project's bug-tracker, showing tasks left for the Qt 5 release:

jira2gv --server https://bugreports.qt-project.org --issue QTBUG-20885 --edgeExtra QTBUG-24203=[minlen=2] --edgeExtra QTBUG-24131=[minlen=3]

=back

=cut

use XML::Simple;
use LWP::Simple;
use HTML::Entities;
use Data::Dumper;
use Switch;
use Text::Wrap   qw(wrap $columns fill);
use Pod::Usage   qw(pod2usage);
use Getopt::Long qw(GetOptionsFromArray );
use POSIX        qw(strftime);

sub parse_arguments
{
    my ($self, @args) = @_;

    %{$self} = (%{$self},
        'verbose'             => 0,
        'doCaching'           => 0,
        'jiraServer'          => "" ,
        'jiraIssue'           => "" ,
        'jiraStopIssues'      => {},
        'gvEdgeExtra'        => {},
        'allOpenIssues'       => {},
        'totalItems'          => 0,
        'remainingIssues'     => [],
    );

    GetOptionsFromArray(\@args,
        'verbose|v'         =>  \$self->{qw{ verbose           }},
        'cache|c'           =>  \$self->{qw{ doCaching         }},
        'server=s'          =>  \$self->{qw{ jiraServer        }},
        'issue=s'           =>  \$self->{qw{ jiraIssue         }},
        'edgeExtra=s%'      =>  \$self->{qw{ gvEdgeExtra      }},
        'issueStop=s'       =>  sub {
            my ($opt, $val) = @_;
            $self->{'jiraStopIssues'}{$val} = 1;
        },
        'help|?'            =>  sub { pod2usage(1); },
    ) || pod2usage(2);

    die "Need to specify a server!" if (!$self->{jiraServer});
    die "Need to specify an issue!" if (!$self->{jiraIssue});

    return;
}

sub createGvItem
{
    my ($self, $item_ref) = @_;

    my $result = "";
    my $id = $item_ref->{'key'}->{'content'};

    my $description = $item_ref->{'summary'};
    $description = wrap("", "", "$description");
    encode_entities($description);
    $description =~ s/\n/<BR \/>/g;

    my $assignee = $item_ref->{'assignee'}->{'content'};
    encode_entities($assignee);

    my $priority = $item_ref->{'priority'}->{'content'};
    my $color;
    switch ($priority) {
        case /^P0/ { $color = "firebrick" }
        case /^P1/ { $color = "red" }
        case /^P2/ { $color = "gold" }
        case /^P3/ { $color = "forestgreen" }
        case /^Not/ { $color = "lightgrey" }
        else       { $color = "steelblue" }
    }

    $result .= "\"$id\" [shape=none,margin=0,color=\"$color\","
             . "label=<<TABLE ALIGN=\"LEFT\" BORDER=\"1\" CELLBORDER=\"0\" COLOR=\"black\">"
             . "<TR><TD ALIGN=\"LEFT\"><B>$id</B></TD><TD ALIGN=\"CENTER\"><B>"
             . $priority . "</B></TD><TD ALIGN=\"RIGHT\">"
             . $assignee . "</TD></TR>";
    $result .= "<TR><TD ALIGN=\"LEFT\" colspan=\"3\">"
             . $description . "</TD></TR></TABLE>>]\n";
    $result .= "\"$id\" [tooltip=\"$id ($priority for $assignee)\", URL=\"" . $item_ref->{'link'} . "\"]\n";

    return $result;
}

sub fetchIssue
{
    my ($self, $issue) = @_;

    my $gvContent = "";
    print "fetching $issue..." if ($self->{verbose});

    my $content;
    if ($self->{doCaching} && -e "$issue.xml") {
        open FILE, "<$issue.xml";
        $content = do { local $/; <FILE> };
        close FILE;
    } else {
        my $url = $self->{jiraServer} . '/si/jira.issueviews:issue-xml/' . $issue . '/' . $issue . '.xml';
        $content = get($url) || die "Couldn't download $issue from $self->{jiraServer}! (using $url)";
        open FILE, ">$issue.xml";
        print FILE $content;
        close FILE;
    }
    my $ref = XMLin($content);

#    if ($issue eq "QTBUG-24203" || $issue eq "QTBUG-20885") {
#        open FILE, ">$issue.pl";
#        print FILE Dumper($ref);
#        close FILE;
#    }
    my $taskStatus = $ref->{'channel'}->{'item'}->{'status'}->{'content'};

    # Ignore tasks which are already closed or resolved
    if ($taskStatus eq "Closed" || $taskStatus eq "Resolved" ) {
        print "[- $taskStatus -]\n" if ($self->{verbose});
        return "";
    }

    $gvContent .= $self->createGvItem($ref->{'channel'}->{'item'});
    print "[done!]\n" if ($self->{verbose});

    # Check if this is a task we stop at, then don't dive into sub-tasks here
    my $stopIssue = $self->{'jiraStopIssues'}->{$issue};
    if (!$stopIssue) {
        # Push each sub-task of this task to the issueLinks hash
        my $sref = $ref->{'channel'}->{'item'}->{'subtasks'}->{'subtask'};
        if ($sref->{'content'}) {
                push(@{$self->{'issueLinks'}{$issue}}, $sref->{'content'});
                $gvContent .=  $self->fetchIssue($sref->{'content'});

        } else {
            foreach my $item (keys %{$sref}) {
                my $subissue = $sref->{$item}->{'content'};
                push(@{$self->{'issueLinks'}{$issue}}, $subissue);
                $gvContent .=  $self->fetchIssue($subissue);
            }
        }

        # Push each outward linke of this task to the issueLinks hash
        if (exists $ref->{'channel'}->{'item'}->{'issuelinks'}->{'issuelinktype'}->{'outwardlinks'}) {
            my $iref = $ref->{'channel'}->{'item'}->{'issuelinks'}->{'issuelinktype'}->{'outwardlinks'}->{'issuelink'};
            if (ref($iref) eq "ARRAY") {
                foreach my $item_ref (@{$ref->{'channel'}->{'item'}->{'issuelinks'}->{'issuelinktype'}->{'outwardlinks'}->{'issuelink'}}) {
                    my $subissue = $item_ref->{'issuekey'}->{'content'};
                    push(@{$self->{'issueLinks'}{$issue}}, $subissue);
                    $gvContent .=  $self->fetchIssue($subissue);
                }
            } elsif (ref($iref) eq "HASH") {
                my $subissue = $iref->{'issuekey'}->{'content'};
                push(@{$self->{'issueLinks'}{$issue}}, $subissue);
                $gvContent .=  $self->fetchIssue($subissue);
            }
        }
    }

    ++$self->{'totalItems'};
    $self->{'allOpenIssues'}{$issue} = 1;
    return $gvContent;
}

sub fetchAllRelatedIssues
{
    my ($self, $issue) = @_;
    push (@{$self->{'remainingIssues'}}, $issue);

    my $gvContent = "";
    while(@{$self->{'remainingIssues'}}) {
        $gvContent .= $self->fetchIssue(shift(@{$self->{'remainingIssues'}}));
    }
    return $gvContent;
}

sub calculateDependencies()
{
    my ($self) = @_;

    my $gvContent = "";
    #print Dumper(\$self->{'issueLinks'});
    my $ref = $self->{'gvEdgeExtra'};
    foreach my $key (keys %{$self->{'issueLinks'}}) {
        if ($self->{'allOpenIssues'}{$key}) {
            foreach my $subissue (@{$self->{'issueLinks'}{$key}}) {
                my $special = $ref->{$subissue};
                $special = "" if (!$special);
                $gvContent .= "\"$key\"->\"$subissue\" $special\n" if ($self->{'allOpenIssues'}{$subissue});
            }
        }
    }
    return $gvContent;
}

sub new
{
    my ($class, @arguments) = @_;

    my $self = {};
    bless $self, $class;
    $self->parse_arguments(@arguments);

    return $self;
}

sub run
{
    my ($self) = @_;

    $columns = 50; # set wrap column for Text::Wrap

    my $jiraIssue = $self->{jiraIssue};
    my $gvContent = << 'EOM';
digraph "Jira issue graph" {
    rankdir=LR
    ranksep=.50
    nodesep=.10
    node [style=filled, fonttype=Helvetica, fontsize=8]
EOM
    my $currentDate = strftime("%Y-%m-%d %H:%M", localtime);
    $gvContent .= $self->fetchAllRelatedIssues($jiraIssue)
                . $self->calculateDependencies() . "\nlabel=\"Jira issue graph for "
                . "$jiraIssue @ $currentDate\"\ntooltip=\" \"\n}\n";

    print "Found $self->{'totalItems'} related items\n" if ($self->{verbose});
    #print $result;
    #print Dumper(\%issueLinks);

    open FILE, ">$jiraIssue.gv";
    print FILE $gvContent;
    close FILE;
}

#==============================================================================

Qt::Jira2Gv->new(@ARGV)->run if (!caller);
1;