blib/lib/App/karr/Cmd/Repair.pm untested

filter: Statementstmt 0.0% 0 / 189 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 63 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 423 CC 53 SCAR 42.3
CC
53
Cov
0%
_survey_stamps
132.0
execute
110.0
_report_stamps
110.0
CRAP 68.8
1 # ABSTRACT: Migrate an old board off double-encoded UTF-8 and off impossible start stamps
2  
3 package App::karr::Cmd::Repair;
4 our $VERSION = '0.602';
5 use Moo;
6 use MooX::Cmd;
7 use MooX::Options (
8 usage_string => 'USAGE: karr repair [--yes] [--json]',
9 );
10 use App::karr::Encoding qw(
11 BOARD_ENCODING_VERSION repair_mojibake
12 yaml_load yaml_dump json_decode json_encode
13 );
14 use App::karr::Task;
15 use App::karr::Role::BoardDiscovery;
16 use App::karr::Role::SyncLifecycle;
17 use App::karr::Role::CliArgs;
18 use App::karr::Role::Output;
19 use App::karr::Error qw( command_hint );
20  
21 with 'App::karr::Role::BoardDiscovery';
22 with 'App::karr::Role::SyncLifecycle';
23 with 'App::karr::Role::CliArgs';
24 with 'App::karr::Role::Output';
25  
26  
27 option yes => (
28 is => 'ro',
29 doc => 'Rewrite the affected refs instead of only reporting them',
30 );
31  
32 sub execute {
33 my ($self, $args_ref, $chain_ref) = @_;
34  
35 $self->check_positional_args($args_ref, 0);
36  
37 my $store = $self->store;
38 my $git = $self->git;
39  
40 # A dry run still pulls (a legacy board may only exist on the remote), but it
41 # must not push, so its guard is closed immediately. --yes takes the full
42 # lifecycle: pull, rewrite, push, with SyncGuard insurance on a crash.
43 my $guard = $self->sync_before;
44 $guard->done unless $self->yes;
45  
46 # Same sentence as everywhere else, with the way out spelled as the command
47 # instead of quoted inside the prose, and last (ticket k263).
48 die "No karr board found:\n" . command_hint('init') . "\n"
49 unless $store->has_board_refs;
50  
51 # The encoding migration is first and is the only one that can be skipped
52 # wholesale: a board already at the current version needs none of it. The
53 # stamp survey below runs on every board, which is why this no longer returns
54 # here the way it did while repair had only the one job.
55 my $legacy = $git->board_is_legacy_encoded ? 1 : 0;
56 my ( $repaired, $skipped ) = ( [], [] );
57 if ($legacy) {
58 ( $repaired, $skipped ) = $self->_repair_refs($git);
59 $git->write_encoding_version if $self->yes;
60 }
61  
62 # Deliberately after the encoding pass, and after the marker: the cards read
63 # here are the cards as they now stand. write_encoding_version invalidates the
64 # cached version, so load_task_ref stops undoing a double encode at exactly
65 # the point the refs stopped carrying one, and a clamped card is written back
66 # once, in its repaired form.
67 my $stamps = $self->_survey_stamps($git);
68 $self->_clamp_started( $git, $stamps->{clamp} ) if $self->yes;
69  
70 $self->sync_after if $self->yes;
71  
72 return $self->_report_json( $git, $legacy, $repaired, $skipped, $stamps )
73 if $self->json;
74  
75 $self->_report_encoding( $git, $legacy, $repaired, $skipped );
76 print "\n";
77 $self->_report_stamps($stamps);
78  
79 # One hint for the whole run, not one per section: both findings are applied
80 # by the same --yes, and printing it twice made the report read as two
81 # separate offers.
82 print "\nTo apply:\n" . command_hint( 'repair', '--yes' ) . "\n"
83 if !$self->yes && ( @$repaired || @{ $stamps->{clamp} } );
84 }
85  
86 sub _report_encoding {
87 my ( $self, $git, $legacy, $repaired, $skipped ) = @_;
88  
89 if ( !$legacy ) {
90 my $version = $git->board_encoding_version;
91 print "Board encoding is already at version $version; nothing to repair.\n";
92 return;
93 }
94  
95 # Never quietly: a ref this could not handle is left as it was, and the marker
96 # goes on regardless, so the user has to be told which ones to look at.
97 if (@$skipped) {
98 printf STDERR "Left %d ref(s) unchanged (could not parse, or not a known board payload):\n", scalar @$skipped;
99 print STDERR " $_\n" for @$skipped;
100 }
101  
102 if ( !@$repaired ) {
103 print $self->yes
104 ? "No double-encoded payloads found; marked the board as encoding version "
105 . BOARD_ENCODING_VERSION . ".\n"
106 : "No double-encoded payloads found. Run with --yes to mark the board as encoding version "
107 . BOARD_ENCODING_VERSION . ".\n";
108 return;
109 }
110  
111 printf "%s %d ref(s):\n", ( $self->yes ? 'Repaired' : 'Would repair' ), scalar @$repaired;
112 print " $_\n" for @$repaired;
113 }
114  
115 # The two costs of the clamp are stated here and nowhere else in the run, in the
116 # indicative and about this board's own cards, because after --yes neither of
117 # them can be read back out of the data (ticket #138).
118 sub _report_stamps {
119 my ( $self, $stamps ) = @_;
120 my @ids = map { $_->id } @{ $stamps->{clamp} };
121  
122 if ( !@ids ) {
123 print "No card carries a bare-date 'started' that precedes its own 'created'.\n";
124 }
125 elsif ( $self->yes ) {
126 printf "Raised 'started' to 'created' on %d card(s): %s\n",
127 scalar @ids, join( ', ', @ids );
128 print <<'END_APPLIED';
129 Those cards now say the work began the instant the card was filed. That is not
130 what happened: karr wrote 'started' as a bare date before ticket #68, so the
131 real start was only ever known to the day, and a card filed in the morning and
132 picked up at night now reports no queue time at all. Nothing on the cards marks
133 the stamp as having been day-granular any more, so this run cannot be told from
134 real data afterwards, and cannot be undone from it.
135 END_APPLIED
136 }
137 else {
138 printf "Would raise 'started' to 'created' on %d card(s): %s\n",
139 scalar @ids, join( ', ', @ids );
140 print <<'END_DRY';
141 Each of those cards would then say the work began the instant the card was
142 filed -- no queue time -- which is false for one filed in the morning and picked
143 up at night, and nothing on the card would mark the stamp as having been
144 day-granular any more. The clamp cannot be undone from the data afterwards.
145 END_DRY
146 }
147  
148 # The one cost the clamp creates rather than inherits, and the reason it gets
149 # its own line instead of a row in the survey below: `completed` was written
150 # day-granular by the same old karr, so raising `started` to a `created` later
151 # in that day steps over it. Such a card's cycle time reads negative
152 # afterwards, where before the clamp it was merely absent.
153 if ( my @over = @{ $stamps->{clamped_over_completed} } ) {
154 my $one = @over == 1;
155 printf
156 "%d of them %s a bare-date 'completed' that %s before the new 'started'.\n"
157 . "karr wrote that stamp day-granular too and this command does not touch it,\n"
158 . "so %s cycle time %s negative: %s\n",
159 scalar @over,
160 ( $one ? 'carries' : 'carry' ),
161 ( $self->yes ? 'falls' : 'would fall' ),
162 ( $one ? 'its' : 'their' ),
163 ( $self->yes ? 'reads' : 'would read' ),
164 join( ', ', @over );
165 }
166  
167 my @found = grep { @{ $stamps->{ $_->[0] } } } (
168 [ started_before_created_unclamped =>
169 "'started' precedes 'created' in a shape this repair does not recognise"
170 . " as the pre-#68 bare-date stamp" ],
171 [ completed_before_started => "'completed' precedes 'started'" ],
172 [ completed_before_created => "'completed' precedes 'created'" ],
173 [ updated_before_created => "'updated' precedes 'created'" ],
174 [ unreadable_stamps => "a stamp in a shape karr cannot compare" ],
175 [ unparseable_cards => "a ref that does not parse as a card at all,"
176 . " so its stamps were not examined" ],
177 );
178 return unless @found;
179  
180 printf "\nFound and NOT repaired -- this command clamps 'started' only.\n"
181 . "Counted as the stamps %s:\n",
182 ( $self->yes ? 'now stand' : 'would stand after --yes' );
183 for my $row (@found) {
184 my ( $key, $what ) = @$row;
185 my @rows = @{ $stamps->{$key} };
186 printf " %d card(s) with %s: %s\n", scalar @rows, $what, join( ', ', @rows );
187 }
188 }
189  
190 sub _report_json {
191 my ( $self, $git, $legacy, $repaired, $skipped, $stamps ) = @_;
192 return $self->print_json({
193 version =>
194 !$legacy ? $git->board_encoding_version
195 : $self->yes ? BOARD_ENCODING_VERSION
196 : 1,
197 up_to_date => $legacy ? \0 : \1,
198 applied => $self->yes ? \1 : \0,
199 repaired => $repaired,
200 skipped => $skipped,
201 started_clamped => [ map { $_->id + 0 } @{ $stamps->{clamp} } ],
202 started_clamped_over_completed => $stamps->{clamped_over_completed},
203 stamp_anomalies => {
204 map { $_ => $stamps->{$_} }
205 qw( started_before_created_unclamped completed_before_started
206 completed_before_created updated_before_created
207 unreadable_stamps unparseable_cards )
208 },
209 });
210 }
211  
212 # Returns ( \@changed, \@unparseable ). Anything whose stored text is pure ASCII
213 # is skipped outright rather than parsed and re-serialized: that is what makes
214 # "does not touch ASCII data" a property of the code rather than a property of
215 # the repair heuristic.
216 sub _repair_refs {
217 my ( $self, $git ) = @_;
218 my ( @repaired, @skipped );
219  
220 for my $ref ( sort $git->list_refs('refs/karr/') ) {
221 my $content = $git->read_ref($ref);
222 next unless defined $content && length $content;
223 next unless $content =~ /[^\x00-\x7F]/;
224  
225 # A non-ASCII payload under refs/karr/ that is none of the three known
226 # shapes is reported rather than passed over: it may well be legacy-encoded
227 # too, and the marker is about to say the whole board is clean.
228 my $known =
229 $ref =~ m{\Arefs/karr/tasks/\d+/data\z}
230 || $ref eq 'refs/karr/config'
231 || $ref =~ m{\Arefs/karr/log/};
232 if ( !$known ) {
233 push @skipped, $ref;
234 next;
235 }
236  
237 my $fixed =
238 $ref eq 'refs/karr/config' ? $self->_repair_config($content)
239 : $ref =~ m{\Arefs/karr/log/} ? $self->_repair_log($content)
240 : $self->_repair_task($content);
241  
242 if ( !defined $fixed ) {
243 push @skipped, $ref;
244 next;
245 }
246  
247 # read_ref chomps one trailing newline and the re-serialized document has
248 # one, so compare with that difference normalized away. Without this every
249 # task whose *body* has non-ASCII -- a body was never double-encoded and
250 # needs no repair -- looked changed and got rewritten for nothing: 63 refs
251 # instead of 17 on karr's own board.
252 ( my $comparable = $fixed ) =~ s/\n\z//;
253 next if $comparable eq $content;
254  
255 push @repaired, $ref;
256 $git->write_ref( $ref, $fixed ) if $self->yes;
257 }
258  
259 return ( \@repaired, \@skipped );
260 }
261  
262 # The pre-#68 `started`, and the shape karr has written for every other stamp
263 # since the beginning. Nothing else is a karr stamp, and nothing else is
264 # clamped.
265 my $BARE_DATE_STAMP = qr/\A\d{4}-\d{2}-\d{2}\z/;
266 my $KARR_STAMP = qr/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\z/;
267  
268 # Both shapes as one string that sorts chronologically, or undef for anything
269 # else. A bare date becomes midnight UTC -- which is not a normalisation, it is
270 # what the stamp already meant, and precisely why it lands before a card created
271 # later the same day.
272 #
273 # This is why no third copy of App::karr::Cmd::Metrics' _epoch is needed here:
274 # both results are the same canonical UTC spelling, so `lt` answers "earlier
275 # than" exactly. It is also why a stamp carrying an offset (kanban-md writes
276 # RFC3339 with a local one) is refused rather than compared -- string order
277 # stops meaning time order the moment two stamps sit in different zones, and a
278 # command that rewrites refs must not guess there.
279 sub _utc_key {
280 my ($stamp) = @_;
281 return undef unless defined $stamp && length $stamp;
282 return $stamp . 'T00:00:00Z' if $stamp =~ $BARE_DATE_STAMP;
283 return $stamp if $stamp =~ $KARR_STAMP;
284 return undef;
285 }
286  
287 # Walks every card once and sorts its lifecycle stamps into the buckets the
288 # report prints. `clamp` holds task objects (they are about to be written);
289 # every other bucket holds ids, because nothing acts on them.
290 #
291 # Cards are loaded one ref at a time under eval rather than through
292 # BoardStore/load_tasks: a ref that does not parse must be counted and reported,
293 # not allowed to kill a repair run halfway through -- that is the same junk ref
294 # the encoding pass above already answers for by name.
295 sub _survey_stamps {
296 my ( $self, $git ) = @_;
297  
298 my %found = map { $_ => [] } qw(
299 clamp clamped_over_completed
300 started_before_created_unclamped completed_before_started
301 completed_before_created updated_before_created
302 unreadable_stamps unparseable_cards
303 );
304  
305 for my $id ( $git->list_task_refs ) {
306 my $task = eval { $git->load_task_ref($id) };
307 if ( !defined $task ) {
308 push @{ $found{unparseable_cards} }, $id + 0;
309 next;
310 }
311  
312 my $created = _utc_key( $task->created );
313 my $updated = _utc_key( $task->updated );
314 my $started = $task->has_started ? _utc_key( $task->started ) : undef;
315 my $completed = $task->has_completed ? _utc_key( $task->completed ) : undef;
316  
317 push @{ $found{unreadable_stamps} }, $id + 0
318 if !defined $created
319 || !defined $updated
320 || ( $task->has_started && !defined $started )
321 || ( $task->has_completed && !defined $completed );
322  
323 if ( defined $created && defined $started && $started lt $created ) {
324 # Only the known bug is migrated. A start that precedes its card while
325 # carrying a time of day is a different fault with an unknown cause, and
326 # clamping it would destroy the only evidence that it happened.
327 if ( $task->started =~ $BARE_DATE_STAMP && $task->created =~ $KARR_STAMP ) {
328 push @{ $found{clamp} }, $task;
329 # The clamp's own doing, called out separately in the report: the same
330 # old karr wrote `completed` day-granular as well, so the new start can
331 # land after it.
332 push @{ $found{clamped_over_completed} }, $id + 0
333 if defined $completed && $completed lt $created;
334 $started = $created;
335 }
336 else {
337 push @{ $found{started_before_created_unclamped} }, $id + 0;
338 }
339 }
340  
341 # Everything below describes the board the run leaves behind -- $started is
342 # the clamped value where the clamp applies. A survey taken before the write
343 # would report an ordering the very same run then breaks, and the user would
344 # first see it on the next invocation.
345 push @{ $found{completed_before_started} }, $id + 0
346 if defined $completed && defined $started && $completed lt $started;
347 push @{ $found{completed_before_created} }, $id + 0
348 if defined $completed && defined $created && $completed lt $created;
349 push @{ $found{updated_before_created} }, $id + 0
350 if defined $updated && defined $created && $updated lt $created;
351 }
352  
353 return \%found;
354 }
355  
356 # Through Git::save_task_ref, not BoardStore::save_task: that one bumps
357 # `updated` on every write to an existing ref, and a migration that re-dated 75
358 # cards to the moment it ran would destroy more history than it repaired. The
359 # encoding pass above writes for the same reason.
360 sub _clamp_started {
361 my ( $self, $git, $tasks ) = @_;
362 for my $task (@$tasks) {
363 $task->started( $task->created );
364 $git->save_task_ref($task);
365 }
366 return;
367 }
368  
369 sub _repair_task {
370 my ( $self, $content ) = @_;
371 my $task = eval { App::karr::Task->from_string( $content, repair_frontmatter => 1 ) };
372 return undef unless $task;
373 return $task->to_markdown;
374 }
375  
376 sub _repair_config {
377 my ( $self, $content ) = @_;
378 my $data = eval { yaml_load($content) };
379 return undef unless ref $data eq 'HASH';
380 return yaml_dump( repair_mojibake($data) );
381 }
382  
383 sub _repair_log {
384 my ( $self, $content ) = @_;
385 my @lines;
386 for my $line ( split /\n/, $content ) {
387 next unless length $line;
388 my $entry = eval { json_decode($line) };
389 return undef unless $entry;
390 push @lines, json_encode( repair_mojibake($entry) );
391 }
392 return join "\n", @lines;
393 }
394  
395 1;
396  
397 __END__