aboutsummaryrefslogtreecommitdiff
path: root/cli/check.translation.php
blob: dbb5d0fe4587f6db1eaaca551ea64bcbe3695aaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env php
<?php
declare(strict_types=1);
require_once __DIR__ . '/_cli.php';
require_once __DIR__ . '/i18n/I18nCompletionValidator.php';
require_once __DIR__ . '/i18n/I18nData.php';
require_once __DIR__ . '/i18n/I18nFile.php';
require_once __DIR__ . '/i18n/I18nUsageValidator.php';
require_once dirname(__DIR__) . '/constants.php';

$cliOptions = new class extends CliOptionsParser {
	/** @var array<int,string> $language */
	public array $language;
	public bool $displayResult;
	public bool $help;
	public bool $displayReport;
	public bool $generateReadme;

	public function __construct() {
		$this->addOption('language', (new CliOption('language', 'l'))->typeOfArrayOfString());
		$this->addOption('displayResult', (new CliOption('display-result', 'd'))->withValueNone());
		$this->addOption('help', (new CliOption('help', 'h'))->withValueNone());
		$this->addOption('displayReport', (new CliOption('display-report', 'r'))->withValueNone());
		$this->addOption('generateReadme', (new CliOption('generate-readme', 'g'))->withValueNone());
		parent::__construct();
	}
};

if (!empty($cliOptions->errors)) {
	fail('FreshRSS error: ' . array_shift($cliOptions->errors) . "\n" . $cliOptions->usage);
}
if ($cliOptions->help) {
	checkHelp();
}

$i18nFile = new I18nFile();
$i18nData = new I18nData($i18nFile->load());

if (isset($cliOptions->language)) {
	$languages = $cliOptions->language;
} else {
	$languages = $i18nData->getAvailableLanguages();
}

$isValidated = true;
$result = [];
$report = [];
$percentage = [];

foreach ($languages as $language) {
	if ($language === $i18nData::REFERENCE_LANGUAGE) {
		$i18nValidator = new I18nUsageValidator($i18nData->getReferenceLanguage(), findUsedTranslations());
	} else {
		$i18nValidator = new I18nCompletionValidator($i18nData->getReferenceLanguage(), $i18nData->getLanguage($language));
	}
	$isValidated = $i18nValidator->validate() && $isValidated;

	$report[$language] = sprintf('%-5s - %s', $language, $i18nValidator->displayReport());
	$percentage[$language] = $i18nValidator->displayReport(percentage_only: true);
	$result[$language] = $i18nValidator->displayResult();
}

if ($cliOptions->displayResult) {
	foreach ($result as $lang => $value) {
		echo 'Language: ', $lang, PHP_EOL;
		print_r($value);
		echo PHP_EOL;
	}
}

if ($cliOptions->displayReport) {
	foreach ($report as $value) {
		echo $value;
	}
}

function writeToReadme(string $readmePath, string $markdownTable): void {
	$language = explode('.', $readmePath)[1];
	// expecting `README.md` for `en` or `README.fr.md` for `fr`
	if ($language === 'md') {
		$language = 'en';
	}
	Minz_Translate::init($language);
	$placeholders = [];
	if (preg_match_all('/__.*?__/', $markdownTable, $placeholders) === false) {
		echo 'Error: Fail while matching translation placeholders', PHP_EOL;
		exit(1);
	}
	foreach (array_unique($placeholders[0]) as $_ => $placeholder) {
		$markdownTable = str_replace($placeholder, _t('gen.readme.' . substr($placeholder, 2, -2)), $markdownTable);
	}

	$readme = file_get_contents($readmePath);
	if ($readme === false) {
		echo 'Error: Unable to open ' . $readmePath, PHP_EOL;
		exit(1);
	}
	if (file_put_contents($readmePath, preg_replace('/<translations>(.*?)<\/translations>/s', <<<EOF
	<translations>
	<!-- This section is automatically generated by `./cli/check.translation.php -g` -->

	$markdownTable

	</translations>
	EOF, $readme)) === false) {
		echo 'Error: Fail while writing to ' . $readmePath, PHP_EOL;
		exit(1);
	}
	echo 'Successfully written translation status into ' . $readmePath, PHP_EOL;
}

if ($cliOptions->generateReadme) {
	$markdownTable = <<<EOF
	| __language__ | __translated__ | |
	| - | - | - |
	EOF;
	$markdownTable .= "\n";

	foreach ($percentage as $lang => $value) {
		$percentageInt = intval(rtrim($value, '%'));
		$completed = intval($percentageInt / 10);
		$uncompleted = intval(ceil((100 - $percentageInt) / 10));
		$progressBar = str_repeat('■', $completed) . str_repeat('・', $uncompleted);

		$ghSearchUrl = 'https://github.com/search?q=' . urlencode("repo:FreshRSS/FreshRSS path:app/i18n/$lang /(TODO|DIRTY)$/");

		$markdownTable .= '| ' . implode(' | ', [
			_t('gen.lang.' . $lang) . " ($lang)",
			$progressBar . ' ' . $percentageInt . '%',
			"[__contribute__]($ghSearchUrl)",
		]) . " |\n";
	}
	// In case we're located in ./cli/
	if (!file_exists('constants.php')) {
		chdir('..');
	}
	foreach (array_merge(['README.md'], glob('README.*.md') ?: []) as $readmePath) {
		writeToReadme($readmePath, rtrim($markdownTable));
	}
	exit();
}

if (!$isValidated) {
	exit(1);
}

/**
 * Find used translation keys in the project
 *
 * Iterates through all php and phtml files in the whole project and extracts all
 * translation keys used.
 *
 * @return list<string>
 */
function findUsedTranslations(): array {
	$directory = new RecursiveDirectoryIterator(__DIR__ . '/..');
	$iterator = new RecursiveIteratorIterator($directory);
	$regex = new RegexIterator($iterator, '/^.+\.(php|phtml)$/i', RecursiveRegexIterator::GET_MATCH);
	$usedI18n = [];
	foreach ($regex as $file => $value) {
		if (!is_string($file) || $file === '') {
			continue;
		}
		$fileContent = file_get_contents($file);
		if ($fileContent === false) {
			continue;
		}
		preg_match_all('/_t\([\'"](?P<strings>[^\'"]+)[\'"]/', $fileContent, $matches);
		$usedI18n = array_merge($usedI18n, $matches['strings']);
	}
	return $usedI18n;
}

/**
 * Output help message.
 */
function checkHelp(): never {
	$file = str_replace(__DIR__ . '/', '', __FILE__);

	echo <<<HELP
NAME
	$file

SYNOPSIS
	php $file [OPTION]...

DESCRIPTION
	Check if translation files have missing keys or missing translations.

	-d, --display-result	display results.
	-h, --help		display this help and exit.
	-l, --language=LANG	filter by LANG.
	-r, --display-report	display completion report.
	-g, --generate-readme	generate translation progress section in readme.

HELP;
	exit();
}