Skip to content

Commit f07659c

Browse files
author
ityaozm@gmail.com
committed
fix(commands): fix handling of JSON decoding errors
- Update decoding of `message` variable in `CommitCommand.php` to handle JSON decoding errors with `JSON_PARTIAL_OUTPUT_ON_ERROR` flag. - Remove control characters from the decoded `message` variable.
1 parent f4a7191 commit f07659c

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

app/Commands/CommitCommand.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ function ($attempts) use ($cachedDiff, $type): string {
103103
}, 'generating...'.PHP_EOL);
104104

105105
$this->task(PHP_EOL.'2. Confirming commit message', function () use (&$message): void {
106-
$message = collect(json_decode($message, true, 512, JSON_THROW_ON_ERROR))
106+
$message = collect(json_decode($message, true, 512, JSON_THROW_ON_ERROR | JSON_PARTIAL_OUTPUT_ON_ERROR))
107107
->map(static function ($content) {
108108
if (\is_array($content)) {
109109
return collect($content)
@@ -348,7 +348,16 @@ private function tryFixMessage(string $message): string
348348
)
349349
->pipe(static function (Stringable $message): Stringable {
350350
return collect([
351-
'/[[:cntrl:]]/mu' => '',
351+
// '/,\s*]/' => ']', // 数组中最后一个元素后的逗号
352+
// '/,\s*}/' => '}', // 对象中最后一个属性后的逗号
353+
// '/:\s*[\[\{]/' => ':[]', // 对象的属性值如果是数组或对象,确保有正确的格式
354+
// '/:\s*null\s*,/' => ':null,', // null 后面不应有逗号
355+
// '/:\s*true\s*,/' => ':true,', // true 后面不应有逗号
356+
// '/:\s*false\s*,/' => ':false,', // false 后面不应有逗号
357+
// '/:\s*"[^"]*"\s*,/' => ':"",', // 字符串后面不应有逗号
358+
// '/,\s*,/' => ',', // 连续的逗号
359+
// '/[\x00-\x1F\x7F-\x9F]/mu' => '', // 控制字符
360+
'/[[:cntrl:]]/mu' => '', // 控制字符
352361
])->reduce(static function (Stringable $message, string $replace, string $pattern): Stringable {
353362
return $message->replaceMatches($pattern, $replace);
354363
}, $message);

tests/Unit/Commands/CommitCommandTest.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
*/
2424

2525
use App\Commands\CommitCommand;
26+
use Pest\Expectation;
2627

2728
it('can try fix message', function (string $message): void {
2829
expect($message)->not->toBeJson()
@@ -31,7 +32,7 @@
3132
return $this->tryFixMessage($message);
3233
})->call(app(CommitCommand::class), $message)
3334
)
34-
->when(true, function (Pest\Expectation $expect) use ($message): void {
35+
->when(true, function (Expectation $expect) use ($message): void {
3536
dump($message, $expect->value);
3637
})
3738
->toBeJson();

0 commit comments

Comments
 (0)