CPAN/Maker/Bootstrapper/Role/LLM/Annotator.pm untested

filter: Statementstmt 0.0% 0 / 266 Branchbran 0.0% 0 / 90 Conditioncond 0.0% 0 / 78 MC/DCmcdc 0.0% 0 / 43 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 517 CC 46 SCAR 40.0
CC
46
Cov
0%
_parse_annotate_file
156.0
cmd_annotate
110.0
cmd_update_annotations
56.0
CRAP 54.6
1 package CPAN::Maker::Bootstrapper::Role::LLM::Annotator;
2 # implements cmd_annotate, cmd_update_annotations
3  
4 use strict;
5 use warnings;
6  
7 use open ':std', ':encoding(UTF-8)';
8  
9 use CLI::Simple::Constants qw(:booleans);
10 use CLI::Simple::Utils qw(slurp);
11 use CPAN::Maker::Bootstrapper::Constants qw(:all);
12  
13 use Cwd qw(getcwd abs_path);
14 use Data::Dumper;
15 use English qw(-no_match_vars);
16 use File::Basename qw(basename);
17 use File::Copy;
18 use File::Temp qw(tempfile);
19 use JSON;
20 use List::Util qw(none);
21  
22 use Role::Tiny;
23  
24 ########################################################################
25 sub cmd_update_annotations {
26 ########################################################################
27 my ($self) = @_;
28  
29 $self->_load_ASCIITable;
30  
31 my ($file) = $self->get_args;
32  
33 die "ERROR: file argument is required\n"
34 if !$file;
35  
36 die "ERROR: $file not found or inaccessible\n"
37 if !abs_path($file);
38  
39 my ( $review, $review_file ) = $self->_get_latest_review( $file, 'code' );
40  
41 die "ERROR: no review file found for $file\n"
42 if !$review || !$review_file;
43  
44 ( my $annotate_file = $review_file ) =~ s/[.]\w+\z/.annotate/xsm;
45  
46 if ( !-e $annotate_file ) {
47 my $generated = $self->_generate_annotate_file( $review, $review_file );
48 printf {*STDOUT} "Generated %s - edit and re-run to apply.\n", $generated;
49 return $SUCCESS;
50 }
51  
52 my $parsed = $self->_parse_annotate_file($annotate_file);
53 my $applied = $self->_apply_annotate_file( $review, $parsed );
54  
55 my ( $fh, $tempfile ) = tempfile( 'annotations-XXXX', DIR => getcwd );
56  
57 die "ERROR: could not create temporary annotations file\n$OS_ERROR\n"
58 if !$fh;
59  
60 print {$fh} JSON->new->pretty->utf8->encode($review);
61  
62 close $fh
63 or die "ERROR: could not close temporary annotations file\n";
64  
65 rename $tempfile, $review_file
66 or die "ERROR: could not save $review_file\n$OS_ERROR\n";
67  
68 printf {*STDOUT} "Applied %d disposition%s from %s\n\n", $applied, $applied == 1 ? q{} : 's', $annotate_file;
69  
70 $self->_show_annotations( $review, $review_file );
71  
72 return $SUCCESS;
73 }
74  
75 ########################################################################
76 sub cmd_annotate {
77 ########################################################################
78 my ($self) = @_;
79  
80 $self->_load_ASCIITable;
81  
82 my ( $file, $api_key ) = $self->get_args;
83  
84 die "ERROR: $file is a required argument\n"
85 if !$file;
86  
87 die "ERROR: $file not found or inaccessible\n"
88 if !abs_path($file);
89  
90 my ( $review, $review_file ) = $self->_get_latest_review( $file, 'code' );
91  
92 die "ERROR: nothing to annotate. No review file found.\n"
93 if !$review_file;
94  
95 # only save if things have changed
96 if ( $self->_annotate($review) ) {
97  
98 my ( $fh, $tempfile ) = tempfile( 'annotations-XXXX', DIR => getcwd );
99  
100 die "ERROR: could not create temporary annotations file\n$OS_ERROR\n"
101 if !$fh;
102  
103 print {$fh} JSON->new->pretty->utf8->encode($review);
104  
105 close $fh
106 or die "ERROR: could not close temporary annotations file!\n";
107  
108 rename $tempfile, $review_file
109 or die "ERROR: could not save $review_file\n$OS_ERROR\n";
110 }
111  
112 $self->_show_annotations( $review, $review_file );
113  
114 if ( $self->get_finalize_annotations ) {
115 $self->_finalize_annotations( $review, $review_file );
116 }
117 elsif ( $self->get_auto_annotate ) {
118 # resubmit for review
119 my $llm_rsp = $self->_cmd_review(
120 type => 'code',
121 file => $file,
122 review => $review,
123 model => $review->{model} // $DEFAULT_CODE_REVIEW_MODEL,
124 api_key => $api_key,
125 context_files => $self->get_context,
126 );
127  
128 return $FAILURE
129 if !$llm_rsp;
130  
131 $self->_print_token_usage( $llm_rsp, 'Code Review: Token Usage Report' );
132 }
133 else {
134 # keep .annotate file in sync with review JSON
135 if ( -e ( my $annotate_file = $review_file =~ s/[.]\w+\z/.annotate/xsmr ) ) {
136 $self->_generate_annotate_file( $review, $review_file );
137 }
138 }
139  
140 return $SUCCESS;
141 }
142  
143 ########################################################################
144 sub _show_annotations {
145 ########################################################################
146 my ( $self, $review, $review_file ) = @_;
147  
148 my $color_on = eval {
149 require Term::ANSI::Color;
150 Term::ANSIColor->import('colored');
151 return 1;
152 };
153  
154 $color_on = $color_on && $self->get_color;
155  
156 my $t = Text::ASCIITable->new( { headingText => "Annotations: $review_file", allowANSI => $color_on } );
157  
158 $t->setCols( 'ID', 'Function', 'Severity', 'Disposition', 'Description' );
159 $t->setColWidth( 'ID', 4 );
160 $t->setColWidth( 'Function', 30 );
161 $t->setColWidth( 'Severity', $color_on ? 20 : 12 );
162 $t->setColWidth( 'Disposition', $color_on ? 20 : 12 );
163 $t->setColWidth( 'Description', 40 );
164  
165 my $findings = $review->{findings} // [];
166  
167 my $pending = 0;
168  
169 foreach my $f ( sort { $a->{id} <=> $b->{id} } @{$findings} ) {
170 my $disposition = $f->{disposition} // q{-};
171  
172 if ( $disposition eq q{-} ) {
173 $pending++;
174 }
175  
176 my $severity = $f->{severity};
177 $t->addRow(
178 $f->{id}, $f->{function},
179 $color_on ? colored( [ $COLORS->{$severity} // 'white' ], $severity ) : $severity,
180 $color_on ? colored( [ $COLORS->{ uc $disposition } // 'white' ], $disposition ) : $disposition,
181 $f->{description},
182 );
183 }
184  
185 print {*STDOUT} $t;
186  
187 my $total = scalar @{$findings};
188 my $applied = $total - $pending;
189  
190 printf {*STDOUT} "%d of %d annotated. %d pending.\n\n", $applied, $total, $pending;
191  
192 return;
193 }
194  
195 ########################################################################
196 sub _generate_annotate_file {
197 ########################################################################
198 my ( $self, $review, $review_file ) = @_;
199  
200 ( my $annotate_file = $review_file ) =~ s/[.]\w+\z/.annotate/xsm;
201  
202 open my $fh, '>', $annotate_file
203 or die "ERROR: could not open $annotate_file for writing\n$OS_ERROR";
204  
205 printf {$fh} "# source: %s\n", $review_file;
206 printf {$fh} "# model: %s\n", $review->{model} // 'unknown';
207 printf {$fh} "# Dispositions: %s\n\n", join q{ }, sort keys %{$DISPOSITIONS};
208  
209 foreach my $f ( sort { $a->{id} <=> $b->{id} } @{ $review->{findings} } ) {
210 printf {$fh} "[%d]\n", $f->{id};
211 printf {$fh} "# %s | %s\n", $f->{function} // 'unknown', $f->{severity};
212 printf {$fh} "# %s\n", $f->{description};
213 printf {$fh} "disposition: %s\n", $f->{disposition} // q{};
214 printf {$fh} "comment: %s\n\n", $f->{comment} // q{};
215 }
216  
217 close $fh
218 or warn "WARNING: could not close $annotate_file: $OS_ERROR\n";
219  
220 return $annotate_file;
221 }
222  
223 ########################################################################
224 sub _parse_annotate_file {
225 ########################################################################
226 my ( $self, $annotate_file ) = @_;
227  
228 open my $fh, '<', $annotate_file
229 or die "ERROR: could not open $annotate_file for reading\n$OS_ERROR";
230  
231 my %parsed;
232 my $current_id;
233 my @comment_lines;
234  
235 while ( my $line = <$fh> ) {
236 chomp $line;
237  
238 next if $line =~ /\A#/xsm; # skip comment lines
239 next if $line =~ /\A\s*\z/xsm && !defined $current_id; # skip leading blanks
240  
241 if ( $line =~ /\A\[(\d+)\]\z/xsm ) {
242 if ( defined $current_id ) {
243 $parsed{$current_id}{comment} = join "\n", @comment_lines;
244 }
245 $current_id = $1;
246 @comment_lines = ();
247 $parsed{$current_id} = {};
248 next;
249 }
250  
251 next if !defined $current_id;
252  
253 if ( $line =~ /\Adisposition:\s*(.*)\z/xsm ) {
254 my $d = uc $1;
255 $parsed{$current_id}{disposition} = $d if length $d;
256 next;
257 }
258  
259 if ( $line =~ /\Acomment:\s*(.*)\z/xsm ) {
260 push @comment_lines, $1 if length $1;
261 next;
262 }
263  
264 # continuation line for comment
265 if ( $line =~ /\A\s+(.*)\z/xsm ) {
266 push @comment_lines, $1;
267 next;
268 }
269 }
270  
271 # flush final section
272 if ( defined $current_id ) {
273 $parsed{$current_id}{comment} = join "\n", @comment_lines;
274 }
275  
276 close $fh
277 or warn "WARNING: could not close $annotate_file: $OS_ERROR\n";
278  
279 return \%parsed;
280 }
281 ########################################################################
282 sub _apply_annotate_file {
283 ########################################################################
284 my ( $self, $review, $parsed ) = @_;
285  
286 my $applied = 0;
287  
288 foreach my $f ( @{ $review->{findings} } ) {
289 my $entry = $parsed->{ $f->{id} }
290 or next;
291  
292 if ( my $d = $entry->{disposition} ) {
293 die sprintf "ERROR: invalid disposition '%s' for finding %d\n", $d, $f->{id}
294 if !$DISPOSITIONS->{$d};
295 $f->{disposition} = $d;
296 $applied++;
297 }
298  
299 # only overwrite comment if the file supplied one
300 if ( defined $entry->{comment} && length $entry->{comment} ) {
301 $f->{comment} = $entry->{comment};
302 }
303 }
304  
305 return $applied;
306 }
307  
308 ########################################################################
309 sub _annotate {
310 ########################################################################
311 my ( $self, $review ) = @_;
312  
313 my @annotations = @{ $self->get_annotate || [] };
314  
315 return
316 if !@annotations;
317  
318 my $batch_comment = $self->get_comment; # may be undef
319  
320 foreach my $a (@annotations) {
321 my ( $finding, $disposition, $inline_comment ) = split /:/, $a, 3;
322 $disposition = uc $disposition;
323  
324 die sprintf "ERROR: invalid disposition, must be n:{disposition} where disposition=%s\n", join q{|}, keys %{$DISPOSITIONS}
325 if !$finding || $finding !~ /^\d+$/xsm || !$disposition || !$DISPOSITIONS->{$disposition};
326  
327 # inline comment beats --comment; --comment beats preserve
328 my $comment = $inline_comment // $batch_comment;
329  
330 $self->_set_finding_disposition( $review, $finding, $disposition, $comment );
331 }
332  
333 return $review;
334 }
335  
336 ########################################################################
337 sub _set_finding_disposition {
338 ########################################################################
339 my ( $self, $review, $finding, $disposition, $comment ) = @_;
340  
341 my $findings = $review->{findings};
342  
343 return
344 if !$findings || !@{$findings};
345  
346 foreach my $f ( @{$findings} ) {
347 next if $finding != $f->{id};
348 $f->{disposition} = $disposition;
349 $f->{comment} = $comment if defined $comment; # preserve existing if not supplied
350 last;
351 }
352  
353 return;
354 }
355  
356 ########################################################################
357 sub _finalize_annotations {
358 ########################################################################
359 my ( $self, $review, $review_file ) = @_;
360  
361 die "ERROR: mark all findings before finalizing!\n"
362 if !$self->_check_annotation_dispositions($review);
363  
364 foreach my $f ( @{ $review->{findings} } ) {
365 next if !$f->{disposition} || $f->{disposition} ne 'WRONG';
366 $f->{disposition} = 'WRONG-RECONSIDER';
367 }
368  
369 my $version = eval { slurp('VERSION') };
370  
371 die "ERROR: could not determine VERSION\n$EVAL_ERROR"
372 if !$version;
373  
374 chomp $version;
375  
376 my ($stem) = $review_file =~ /^(.*?)-review/xsm;
377  
378 my $final_review_file = sprintf '%s-%s.review', $stem, $version;
379 my $final_annotate_file = sprintf '%s-%s.annotate', $stem, $version;
380  
381 # write modified review (with WRONG-RECONSIDER conversions) to final file
382 open my $fh, '>', $final_review_file
383 or die "ERROR: could not open $final_review_file for writing: $OS_ERROR\n";
384  
385 print {$fh} JSON->new->pretty->utf8->encode($review);
386  
387 close $fh
388 or warn "WARNING: could not close $final_review_file: $OS_ERROR\n";
389  
390 # enshrine the annotate file if one exists
391 ( my $annotate_file = $review_file ) =~ s/[.]\w+\z/.annotate/xsm;
392  
393 if ( -e $annotate_file ) {
394 copy $annotate_file, $final_annotate_file
395 or warn "WARNING: could not copy $annotate_file to $final_annotate_file: $OS_ERROR\n";
396 }
397 else {
398 $self->_generate_annotate_file( $review, $final_review_file );
399 }
400  
401 return;
402 }
403  
404 ########################################################################
405 sub _load_ASCIITable {
406 ########################################################################
407  
408 require Text::ASCIITable;
409 require Text::ASCIITable::FixANSI;
410  
411 return;
412 }
413  
414 ########################################################################
415 sub _check_annotation_dispositions {
416 ########################################################################
417 my ( $self, $review ) = @_;
418  
419 return $TRUE
420 if !$review;
421  
422 my @findings = @{ $review->{findings} };
423  
424 return $TRUE
425 if !@findings || none { !defined $_->{disposition} } @findings;
426  
427 return $FALSE;
428 }
429  
430 1;
431  
432 __END__