blib/lib/Git/Hooks/CheckYoutrack.pm untested

filter: Statementstmt 0.0% 0 / 177 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 33 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 283 SCAR 62.3
CC
22
Cov
0%
_get_ticket
42.0
_process_ticket
42.0
check_commit_msg
30.0
CRAP 506.0
1 # ========================================================================== #
2 # lib/Git/Hooks/Youtrack.pm - Github Hooks for youtrack
3 # ========================================================================== #
4  
5 package Git::Hooks::CheckYoutrack;
6  
7 use strict;
8 use warnings;
9 use utf8;
10 use Log::Any '$log';
11 use Path::Tiny;
12 use Git::Hooks;
13 use LWP::UserAgent;
14 use URI::Builder;
15 use JSON::XS;
16  
17 $Git::Hooks::CheckYoutrack::VERSION = '1.0.0';
18  
19 =head1 NAME
20  
21 Git::Hooks::CheckYoutrack - Git::Hooks plugin which requires youtrack ticket number on each commit message
22  
23 =head1 SYNOPSIS
24  
25 As a C<Git::Hooks> plugin you don't use this Perl module directly. Instead, you
26 may configure it in a Git configuration file like this:
27  
28 [githooks]
29
30 # Enable the plugin
31 plugin = CheckYoutrack
32  
33 [githooks "checkyoutrack"]
34  
35 # '/youtrack' will be appended to this host
36 youtrack-host = "https://example.myjetbrains.com"
37  
38 # Refer: https://www.jetbrains.com/help/youtrack/standalone/Manage-Permanent-Token.html
39 # to create a Bearer token
40 youtrack-token = "<your-token>"
41  
42 # Regular expression to match for Youtrack ticket id
43 matchkey = '^((?:P|M)(?:AY|\d+)-\d+)'
44  
45 # Setting this flag will aborts the commit if valid Youtrack number not found
46 # Shows a warning message otherwise - default false
47 required = true
48  
49 # Print the fetched youtrack ticket details like Assignee, State etc..,
50 # default false
51 print-info = true
52  
53  
54 =head1 DESCRIPTION
55  
56 This plugin hooks the following git hooks to guarantee that every commit message
57 cites a valid Youtrack Id in the log message, so that you can be certain that
58 every commit message has a valid link to the Youtrack ticket. Refer L<Git::Hooks Usage|https://metacpan.org/pod/Git::Hooks#USAGE>
59 for steps to install and use Git::Hooks
60  
61 This plugin also hooks prepare-commit-msg to pre-populate youtrack ticket sumary on the
62 commit message if the current working branch name is starting with the valid ticket number
63  
64 =head1 METHODS
65  
66 =cut
67  
68 my $PKG = __PACKAGE__;
69 (my $CFG = __PACKAGE__) =~ s/.*::/githooks./;
70  
71 # =========================================================================== #
72  
73 =head2 B<commit-msg>, B<applypatch-msg>
74
75 These hooks are invoked during the commit, to check if the commit message
76 starts with a valid Youtrack ticket Id.
77  
78 =cut
79  
80 sub check_commit_msg {
81 my ($git, $message) = @_;
82  
83 # Skip for empty message
84 return 'no_check' if (!$message || $message =~ /^[\n\r]$/g);
85  
86 my $yt_id = _get_youtrack_id($git, $message);
87  
88 if (!$yt_id) {
89 return _show_error($git, "Missing youtrack ticket id in your message: $message");
90 }
91  
92 $log->debug("Found Youtrack ticket id from message as: $yt_id");
93  
94 my $yt_ticket = _get_ticket($git, $yt_id);
95  
96 if (!$yt_ticket) {
97 return _show_error($git, "Youtrack ticket not found with ID: $yt_id");
98 }
99  
100 if ($yt_ticket && $git->get_config_boolean($CFG => 'print-info')) {
101 print '-' x 80 . "\n";
102 print "Youtrack ticket: $yt_ticket->{ticket_id}\n";
103 print "Summary: $yt_ticket->{summary}\n";
104 print "Current status: $yt_ticket->{State}\n";
105 print "Assigned to: $yt_ticket->{Assignee}\n";
106 print "Ticket Link: $yt_ticket->{WebLink}\n";
107 print '-' x 80 . "\n";
108 }
109  
110 return 0;
111 }
112  
113 # =========================================================================== #
114  
115 sub check_message_file {
116 my ($git, $commit_msg_file) = @_;
117  
118 $log->debug(__PACKAGE__ . "::check_message_file($commit_msg_file)");
119  
120 _setup_config($git);
121  
122 my $msg = _get_message_from_file($git, $commit_msg_file);
123  
124 # Remove comment lines from the message file contents.
125 $msg =~ s/^#[^\n]*\n//mgs;
126  
127 return check_commit_msg($git, $msg);
128 }
129  
130 # =========================================================================== #
131  
132 sub _show_error {
133 my ($git, $msg) = @_;
134 if ($git->get_config_boolean($CFG => 'required')) {
135 $git->fault("ERROR: $msg");
136 return 1;
137 }
138 else {
139 print "WARNING: $msg\n";
140 return 0;
141 }
142 }
143  
144 # =========================================================================== #
145  
146 sub check_affected_refs {
147 my ($git) = @_;
148  
149 $log->debug(__PACKAGE__ . "::check_affected_refs");
150  
151 _setup_config($git);
152  
153 my $errors = 0;
154  
155 foreach my $ref ($git->get_affected_refs()) {
156 next unless $git->is_reference_enabled($ref);
157 check_ref($git, $ref)
158 or ++$errors;
159 }
160  
161 if($errors) {
162 return _show_error($git, "Some of your commit message missing a valid youtrack ticket");
163 }
164  
165 return 0;
166 }
167  
168 # =========================================================================== #
169  
170 sub check_ref {
171 my ($git, $ref) = @_;
172  
173 my $errors = 0;
174  
175 foreach my $commit ($git->get_affected_ref_commits($ref)) {
176 check_commit_msg($git, $commit->message) or ++$errors;
177 }
178  
179 return $errors == 0;
180 }
181  
182 # =========================================================================== #
183  
184 =head2 B<prepare-commit-msg>
185
186 This hook is invoked before a commit, to check if the current branch name start with
187 a valid youtrack ticket id and pre-populates the commit message with youtrack ticket: summary
188  
189 =cut
190  
191 sub add_youtrack_summary {
192 my ($git, $commit_msg_file) = @_;
193  
194 $log->debug(__PACKAGE__ . "::add_youtrack_summary($commit_msg_file)");
195  
196 _setup_config($git);
197  
198 my $msg = _get_message_from_file($git, $commit_msg_file);
199 my $msg_copy = $msg;
200  
201 # Remove comment lines and empty lines from the message file contents.
202 $msg =~ s/^#[^\n]*\n//mgs;
203 $msg =~ s/^\n*\n$//msg;
204  
205 # Don't do anything if message already exist (user used -m option)
206 if ($msg) {
207 $log->debug("Message exist: $msg");
208 return 0;
209 }
210  
211 my $current_branch = $git->get_current_branch();
212  
213 # Extract current branch name
214 $current_branch =~ s/.+\/(.+)/$1/;
215  
216 my $yt_id = _get_youtrack_id($git, $current_branch);
217  
218 if (!$yt_id) {
219 $log->warn("No youtrack id in your working branch");
220 return 0;
221 }
222  
223 my $task = _get_ticket($git, $yt_id);
224  
225 if (!$task) {
226 $log->warn("Your branch name does not match with youtrack ticket");
227 return 0;
228 }
229  
230 my $ticket_msg = "$yt_id: $task->{summary}\n";
231  
232 $log->debug("Pre-populating commit message as: $ticket_msg");
233  
234 open my $out, '>', path($commit_msg_file) or die "Can't write new file: $!";
235 print $out $ticket_msg;
236 print $out $msg_copy;
237 close $out;
238 }
239  
240 # =========================================================================== #
241  
242 sub _get_message_from_file {
243 my ($git, $file) = @_;
244  
245 my $msg = eval { path($file)->slurp };
246 defined $msg
247 or $git->fault("Cannot open file '$file' for reading:", {details => $@})
248 and return 0;
249  
250 return $msg;
251 }
252  
253 # =========================================================================== #
254  
255 # Setup default configs
256 sub _setup_config {
257 my ($git) = @_;
258  
259 my $config = $git->get_config();
260  
261 $config->{lc $CFG} //= {};
262  
263 my $default = $config->{lc $CFG};
264  
265 # Default matchkey for matching Youtrack ids (P3-1234 || PAY-1234) keys.
266 $default->{matchkey} //= ['^((?:P|M)(?:AY|\d+)-\d+)'];
267  
268 $default->{required} //= ['false'];
269  
270 $default->{'print-info'} //= ['false'];
271  
272 return;
273 }
274  
275 # =========================================================================== #
276  
277 # Tries to get a valid youtrack ticket and return a HashRef with ticket details if found success
278 sub _get_ticket {
279 my ($git, $ticket_id) = @_;
280  
281 my $yt_token = $git->get_config($CFG => 'youtrack-token');
282  
283 $yt_token = $ENV{YoutrackToken} if (!$yt_token);
284  
285 if (!$yt_token) {
286 my $error = "Please set Youtrack permanent token in ENV YoutrackToken\n";
287 $error .= "Refer: https://www.jetbrains.com/help/youtrack/standalone/Manage-Permanent-Token.html\n";
288 $error .= "to generate a token\n";
289 $git->fault($error);
290 return;
291 }
292  
293 my $yt_host = $git->get_config($CFG => 'youtrack-host');
294 my $yt = URI::Builder->new(uri => $yt_host);
295  
296 my $ua = $git->{yt_ua} //= LWP::UserAgent->new();
297 $ua->default_header('Authorization' => "Bearer $yt_token");
298 $ua->default_header('Accept' => 'application/json');
299 $ua->default_header('Content-Type' => 'application/json');
300  
301 my $ticket_fields = 'fields=numberInProject,project(shortName),summary,customFields(name,value(name))';
302  
303 $yt->path_segments("youtrack", "api", "issues", $ticket_id);
304  
305 my $url = $yt->as_string . "?$ticket_fields";
306  
307 my $ticket = $ua->get($url);
308  
309 if (!$ticket->is_success) {
310 $log->debug("Youtrack fetch failed");
311 return;
312 }
313  
314 my $json = decode_json($ticket->decoded_content);
315 my $ticket_details = _process_ticket($json);
316  
317 if (!$ticket_details->{ticket_id}) {
318 $log->debug("No valid youtrack ticket found");
319 return;
320 }
321  
322 $ticket_details->{Assignee} = 'Unassigned' if (!$ticket_details->{Assignee});
323  
324 $yt->path_segments('youtrack', 'issue', $ticket_id);
325 $ticket_details->{WebLink} = $yt->as_string;
326  
327 return $ticket_details;
328 }
329  
330 # =========================================================================== #
331  
332 # Helper method to process the response from Youtrack API
333 sub _process_ticket {
334 my $json = shift;
335  
336 return if (!$json);
337 my $ticket;
338  
339 $ticket->{summary} = $json->{summary};
340 $ticket->{type} = $json->{'$' . 'type'};
341 $ticket->{ticket_id} = $json->{numberInProject};
342  
343 if ($json->{project} && $json->{project}->{shortName}) {
344 $ticket->{ticket_id} = $json->{project}->{shortName} . '-' . $ticket->{ticket_id};
345 }
346  
347 if ($json->{customFields}) {
348 foreach my $field (@{$json->{customFields}}) {
349  
350 if (ref $field->{value} eq 'HASH') {
351 $ticket->{$field->{name}} = $field->{value}->{name};
352 }
353 elsif (ref $field->{value} eq 'ARRAY') {
354 foreach my $val (@{$field->{value}}) {
355 $ticket->{$field->{name}} = join(',', $val->{name});
356 }
357 }
358 else {
359 $ticket->{$field->{name}} = $field->{value};
360 }
361 }
362 }
363  
364 return $ticket;
365 }
366  
367 # =========================================================================== #
368  
369 # Check and return a youtrack Id in the given string based on the matchkey regex
370 sub _get_youtrack_id {
371 my ($git, $message) = @_;
372  
373 my $matchkey = $git->get_config($CFG => 'matchkey');
374  
375 if ($message =~ /$matchkey/i) {
376 return uc($1);
377 }
378  
379 return;
380 }
381  
382 # =========================================================================== #
383  
384 # Install hooks via Git::Hooks
385 APPLYPATCH_MSG \&check_message_file;
386 COMMIT_MSG \&check_message_file;
387 PREPARE_COMMIT_MSG \&add_youtrack_summary;
388 UPDATE \&check_affected_refs;
389  
390 # =========================================================================== #
391  
392 1;
393  
394 __END__