|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ArtARTs36\MergeRequestLinter\Application\Rule\Rules; |
| 4 | + |
| 5 | +use ArtARTs36\MergeRequestLinter\Application\Rule\Definition\Definition; |
| 6 | +use ArtARTs36\MergeRequestLinter\Domain\Note\LintNote; |
| 7 | +use ArtARTs36\MergeRequestLinter\Domain\Request\MergeRequest; |
| 8 | +use ArtARTs36\MergeRequestLinter\Domain\Rule\RuleDefinition; |
| 9 | +use ArtARTs36\MergeRequestLinter\Shared\Text\Ssh\SshKeyFinder; |
| 10 | +use ArtARTs36\Str\Str; |
| 11 | + |
| 12 | +/** |
| 13 | + * Prevent ssh keys from being included in the merge request. |
| 14 | + * @phpstan-import-type SshKeyType from SshKeyFinder |
| 15 | + */ |
| 16 | +final class NoSshKeysRule extends NamedRule |
| 17 | +{ |
| 18 | + public const NAME = '@mr-linter/no_ssh_keys'; |
| 19 | + |
| 20 | + public function __construct( |
| 21 | + private readonly SshKeyFinder $sshKeyFinder, |
| 22 | + private readonly bool $stopOnFirstFailure, |
| 23 | + ) { |
| 24 | + } |
| 25 | + |
| 26 | + public function lint(MergeRequest $request): array |
| 27 | + { |
| 28 | + $notes = []; |
| 29 | + |
| 30 | + foreach ($request->changes as $change) { |
| 31 | + foreach ($change->diff->newFragments as $line) { |
| 32 | + if (! $line->hasChanges()) { |
| 33 | + continue; |
| 34 | + } |
| 35 | + |
| 36 | + $foundTypes = $this->findSshKeysTypes($line->content); |
| 37 | + |
| 38 | + if (count($foundTypes) === 0) { |
| 39 | + continue; |
| 40 | + } |
| 41 | + |
| 42 | + foreach ($foundTypes as $keyType) { |
| 43 | + $notes[] = new LintNote(sprintf( |
| 44 | + 'File "%s" contains ssh key (%s)', |
| 45 | + $change->file, |
| 46 | + $keyType, |
| 47 | + )); |
| 48 | + } |
| 49 | + |
| 50 | + if ($this->stopOnFirstFailure) { |
| 51 | + break 2; |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return $notes; |
| 57 | + } |
| 58 | + |
| 59 | + public function getDefinition(): RuleDefinition |
| 60 | + { |
| 61 | + return new Definition('Request must no contain ssh keys'); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @return array<SshKeyType> |
| 66 | + */ |
| 67 | + private function findSshKeysTypes(Str $content): array |
| 68 | + { |
| 69 | + if ($this->stopOnFirstFailure) { |
| 70 | + $foundSshTypes = []; |
| 71 | + |
| 72 | + $foundSshType = $this->sshKeyFinder->findFirst($content); |
| 73 | + |
| 74 | + if ($foundSshType !== null) { |
| 75 | + $foundSshTypes = [$foundSshType]; |
| 76 | + } |
| 77 | + |
| 78 | + return $foundSshTypes; |
| 79 | + } |
| 80 | + |
| 81 | + return $this->sshKeyFinder->findAll($content); |
| 82 | + } |
| 83 | +} |
0 commit comments