check.translation.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #!/usr/bin/env php
  2. <?php
  3. declare(strict_types=1);
  4. require_once __DIR__ . '/_cli.php';
  5. require_once __DIR__ . '/i18n/I18nCompletionValidator.php';
  6. require_once __DIR__ . '/i18n/I18nData.php';
  7. require_once __DIR__ . '/i18n/I18nFile.php';
  8. require_once __DIR__ . '/i18n/I18nUsageValidator.php';
  9. require_once dirname(__DIR__) . '/constants.php';
  10. $cliOptions = new class extends CliOptionsParser {
  11. /** @var array<int,string> $language */
  12. public array $language;
  13. public bool $displayResult;
  14. public bool $help;
  15. public bool $displayReport;
  16. public bool $generateReadme;
  17. public function __construct() {
  18. $this->addOption('language', (new CliOption('language', 'l'))->typeOfArrayOfString());
  19. $this->addOption('displayResult', (new CliOption('display-result', 'd'))->withValueNone());
  20. $this->addOption('help', (new CliOption('help', 'h'))->withValueNone());
  21. $this->addOption('displayReport', (new CliOption('display-report', 'r'))->withValueNone());
  22. $this->addOption('generateReadme', (new CliOption('generate-readme', 'g'))->withValueNone());
  23. parent::__construct();
  24. }
  25. };
  26. if (!empty($cliOptions->errors)) {
  27. fail('FreshRSS error: ' . array_shift($cliOptions->errors) . "\n" . $cliOptions->usage);
  28. }
  29. if ($cliOptions->help) {
  30. checkHelp();
  31. }
  32. $i18nFile = new I18nFile();
  33. $i18nData = new I18nData($i18nFile->load());
  34. if (isset($cliOptions->language)) {
  35. $languages = $cliOptions->language;
  36. } else {
  37. $languages = $i18nData->getAvailableLanguages();
  38. }
  39. $isValidated = true;
  40. $result = [];
  41. $report = [];
  42. $percentage = [];
  43. foreach ($languages as $language) {
  44. if ($language === $i18nData::REFERENCE_LANGUAGE) {
  45. $usedTranslations = findUsedTranslations();
  46. $referenceLanguage = $i18nData->getReferenceLanguage();
  47. $pluralFamilies = loadPluralReferenceFamilies($referenceLanguage);
  48. if ($pluralFamilies !== []) {
  49. $referenceLanguage['plurals.php'] = $pluralFamilies;
  50. }
  51. $i18nValidator = new I18nUsageValidator($referenceLanguage, $usedTranslations['keys'], $usedTranslations['prefixes']);
  52. } else {
  53. $i18nValidator = new I18nCompletionValidator($i18nData->getReferenceLanguage(), $i18nData->getLanguage($language));
  54. }
  55. $isValidated = $i18nValidator->validate() && $isValidated;
  56. $report[$language] = sprintf('%-5s - %s', $language, $i18nValidator->displayReport());
  57. $percentage[$language] = $i18nValidator->displayReport(percentage_only: true);
  58. $result[$language] = $i18nValidator->displayResult();
  59. }
  60. if ($cliOptions->displayResult) {
  61. foreach ($result as $lang => $value) {
  62. echo 'Language: ', $lang, PHP_EOL;
  63. print_r($value);
  64. echo PHP_EOL;
  65. }
  66. }
  67. if ($cliOptions->displayReport) {
  68. foreach ($report as $value) {
  69. echo $value;
  70. }
  71. }
  72. function writeToReadme(string $readmePath, string $markdownTable): void {
  73. $language = explode('.', $readmePath)[1];
  74. // expecting `README.md` for `en` or `README.fr.md` for `fr`
  75. if ($language === 'md') {
  76. $language = 'en';
  77. }
  78. Minz_Translate::init($language);
  79. $placeholders = [];
  80. if (preg_match_all('/__.*?__/', $markdownTable, $placeholders) === false) {
  81. echo 'Error: Fail while matching translation placeholders', PHP_EOL;
  82. exit(1);
  83. }
  84. foreach (array_unique($placeholders[0]) as $_ => $placeholder) {
  85. $markdownTable = str_replace($placeholder, _t('gen.readme.' . substr($placeholder, 2, -2)), $markdownTable);
  86. }
  87. $readme = file_get_contents($readmePath);
  88. if ($readme === false) {
  89. echo 'Error: Unable to open ' . $readmePath, PHP_EOL;
  90. exit(1);
  91. }
  92. if (file_put_contents($readmePath, preg_replace('/<translations>(.*?)<\/translations>/s', <<<EOF
  93. <translations>
  94. <!-- This section is automatically generated by `./cli/check.translation.php -g` -->
  95. $markdownTable
  96. </translations>
  97. EOF, $readme)) === false) {
  98. echo 'Error: Fail while writing to ' . $readmePath, PHP_EOL;
  99. exit(1);
  100. }
  101. echo 'Successfully written translation status into ' . $readmePath, PHP_EOL;
  102. }
  103. if ($cliOptions->generateReadme) {
  104. $markdownTable = <<<EOF
  105. | __language__ | __translated__ | |
  106. | - | - | - |
  107. EOF;
  108. $markdownTable .= "\n";
  109. foreach ($percentage as $lang => $value) {
  110. $percentageInt = intval(rtrim($value, '%'));
  111. $completed = intval($percentageInt / 10);
  112. $uncompleted = intval(ceil((100 - $percentageInt) / 10));
  113. $progressBar = str_repeat('■', $completed) . str_repeat('・', $uncompleted);
  114. $ghSearchUrl = 'https://github.com/search?q=' . urlencode("repo:FreshRSS/FreshRSS path:app/i18n/$lang /(TODO|DIRTY)$/");
  115. $markdownTable .= '| ' . implode(' | ', [
  116. _t('gen.lang.' . $lang) . " ($lang)",
  117. $progressBar . ' ' . $percentageInt . '%',
  118. "[__contribute__]($ghSearchUrl)",
  119. ]) . " |\n";
  120. }
  121. // In case we're located in ./cli/
  122. if (!file_exists('constants.php')) {
  123. chdir('..');
  124. }
  125. foreach (array_merge(['README.md'], glob('README.*.md') ?: []) as $readmePath) {
  126. writeToReadme($readmePath, rtrim($markdownTable));
  127. }
  128. exit();
  129. }
  130. if (!$isValidated) {
  131. exit(1);
  132. }
  133. /**
  134. * Find used translation keys in the project
  135. *
  136. * Iterates through all php and phtml files in the whole project and extracts all
  137. * translation keys used.
  138. *
  139. * @return array{keys:list<string>,prefixes:list<string>}
  140. */
  141. function findUsedTranslations(): array {
  142. $directory = new RecursiveDirectoryIterator(__DIR__ . '/..', FilesystemIterator::SKIP_DOTS);
  143. $iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD);
  144. $regex = new RegexIterator($iterator, '/^.+\.(php|phtml)$/i', RecursiveRegexIterator::GET_MATCH);
  145. $usedI18n = [];
  146. $usedPrefixes = [];
  147. foreach ($regex as $file => $value) {
  148. if (!is_string($file) || $file === '') {
  149. continue;
  150. }
  151. $fileContent = file_get_contents($file);
  152. if ($fileContent === false) {
  153. continue;
  154. }
  155. preg_match_all('/_t\([\'"](?P<strings>[^\'"]+)[\'"]/', $fileContent, $matches);
  156. $usedI18n = array_merge($usedI18n, $matches['strings']);
  157. preg_match_all('/Minz_Translate::plural\(\s*[\'"](?P<string>[^\'"]+)[\'"](?P<dynamic>\s*\.)?/', $fileContent, $pluralMatches, PREG_SET_ORDER);
  158. foreach ($pluralMatches as $match) {
  159. $string = $match['string'];
  160. if (($match['dynamic'] ?? '') !== '') {
  161. $usedPrefixes[] = $string;
  162. } else {
  163. $usedI18n[] = $string;
  164. }
  165. }
  166. }
  167. return [
  168. 'keys' => array_values(array_unique($usedI18n)),
  169. 'prefixes' => array_values(array_unique($usedPrefixes)),
  170. ];
  171. }
  172. /**
  173. * @param array<string,array<string,I18nValue>> $referenceLanguage
  174. * @return array<string,I18nValue>
  175. */
  176. function loadPluralReferenceFamilies(array $referenceLanguage): array {
  177. $pluralFamilies = [];
  178. foreach ($referenceLanguage as $values) {
  179. foreach ($values as $key => $value) {
  180. if (preg_match('/^(?P<base>.+)\.(?P<index>\d+)$/', $key, $matches) !== 1) {
  181. continue;
  182. }
  183. $baseKey = $matches['base'];
  184. $index = $matches['index'];
  185. $pluralFamilies[$baseKey][(int)$index] = $value->__toString();
  186. }
  187. }
  188. $normalisedFamilies = [];
  189. foreach ($pluralFamilies as $baseKey => $messageFamily) {
  190. $messages = [];
  191. ksort($messageFamily);
  192. foreach ($messageFamily as $message) {
  193. if ($message !== '') {
  194. $messages[] = $message;
  195. }
  196. }
  197. $normalisedFamilies[$baseKey] = new I18nValue(implode(' | ', $messages));
  198. }
  199. return $normalisedFamilies;
  200. }
  201. /**
  202. * Output help message.
  203. */
  204. function checkHelp(): never {
  205. $file = str_replace(__DIR__ . '/', '', __FILE__);
  206. echo <<<HELP
  207. NAME
  208. $file
  209. SYNOPSIS
  210. php $file [OPTION]...
  211. DESCRIPTION
  212. Check if translation files have missing keys or missing translations.
  213. -d, --display-result display results.
  214. -h, --help display this help and exit.
  215. -l, --language=LANG filter by LANG.
  216. -r, --display-report display completion report.
  217. -g, --generate-readme generate translation progress section in readme.
  218. HELP;
  219. exit();
  220. }