|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Recursively find all `plugin.json` files in a directory. |
| 5 | + * |
| 6 | + * @param string $dir Directory to search in. |
| 7 | + * @return array List of file paths. |
| 8 | + */ |
| 9 | +function findPluginJsonFiles(string $dir): array |
| 10 | +{ |
| 11 | + $results = []; |
| 12 | + $files = scandir($dir); |
| 13 | + |
| 14 | + foreach ($files as $file) { |
| 15 | + if ($file === '.' || $file === '..') { |
| 16 | + continue; |
| 17 | + } |
| 18 | + |
| 19 | + $path = $dir . DIRECTORY_SEPARATOR . $file; |
| 20 | + |
| 21 | + if (is_dir($path)) { |
| 22 | + $results = array_merge($results, findPluginJsonFiles($path)); |
| 23 | + } elseif ($file === 'plugin.json') { |
| 24 | + $results[] = $path; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + return $results; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Validate a `plugin.json` file to ensure it does not contain a "meta" key. |
| 33 | + * |
| 34 | + * @param string $file Path to the JSON file. |
| 35 | + * @param string $relativePath Relative path to the file for better output clarity. |
| 36 | + * @return string|null Error message if invalid, or null if valid. |
| 37 | + */ |
| 38 | +function validateJsonFile(string $file, string $relativePath): ?string |
| 39 | +{ |
| 40 | + $content = file_get_contents($file); |
| 41 | + |
| 42 | + if ($content === false) { |
| 43 | + return "Failed to read $relativePath."; |
| 44 | + } |
| 45 | + |
| 46 | + $json = json_decode($content, true); |
| 47 | + |
| 48 | + if (json_last_error() !== JSON_ERROR_NONE) { |
| 49 | + return "Invalid JSON in $relativePath: " . json_last_error_msg(); |
| 50 | + } |
| 51 | + |
| 52 | + if (array_key_exists('meta', $json)) { |
| 53 | + return "$relativePath contains a 'meta' key. Please remove it."; |
| 54 | + } |
| 55 | + |
| 56 | + return null; |
| 57 | +} |
| 58 | + |
| 59 | +$root = realpath(__DIR__ . '/../../'); |
| 60 | +$pluginJsonFiles = findPluginJsonFiles($root); |
| 61 | + |
| 62 | +echo 'Found ' . count($pluginJsonFiles) . " plugin.json file(s) to validate.\n"; |
| 63 | + |
| 64 | +$errors = []; |
| 65 | + |
| 66 | +foreach ($pluginJsonFiles as $file) { |
| 67 | + $relativePath = str_replace($root . DIRECTORY_SEPARATOR, '', $file); |
| 68 | + |
| 69 | + echo "Validating $relativePath...\n"; |
| 70 | + $error = validateJsonFile($file, $relativePath); |
| 71 | + |
| 72 | + if ($error !== null) { |
| 73 | + $errors[] = $error; |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +if (!empty($errors)) { |
| 78 | + echo "\nErrors found in the following plugin.json files:\n"; |
| 79 | + foreach ($errors as $error) { |
| 80 | + echo " - $error\n"; |
| 81 | + } |
| 82 | + exit(1); |
| 83 | +} |
| 84 | + |
| 85 | +echo "All plugin.json files are valid!\n"; |
| 86 | +exit(0); |
0 commit comments