diff --git a/translations/translationtool/.gitignore b/translations/translationtool/.gitignore index 3511f07e..d963dbe9 100644 --- a/translations/translationtool/.gitignore +++ b/translations/translationtool/.gitignore @@ -3,3 +3,6 @@ composer.phar .vscode .php-cs-fixer.cache /tests/translationfiles/templates/tests.pot +/tests-base/translationfiles/ +/tests/src/themes/tests/l10n/de.js +/tests/src/themes/tests/l10n/de.json diff --git a/translations/translationtool/src/translationtool.php b/translations/translationtool/src/translationtool.php index 0d6ceeee..ccbd402a 100644 --- a/translations/translationtool/src/translationtool.php +++ b/translations/translationtool/src/translationtool.php @@ -10,6 +10,13 @@ require __DIR__ . '/vendor/autoload.php'; class TranslatableApp { + /** xgettext keywords and language for each language of languageOf() */ + private const XGETTEXT_ARGUMENTS = [ + 'php' => '--keyword=t --keyword=n:1,2 --language=PHP', + 'python' => '--keyword=_ --keyword=_n:1,2 --language=Python', + 'script' => '--keyword=t:2 --keyword=n:2,3 --language=Javascript', + ]; + private string $appPath; private string $name = ''; private string $fakeAppInfoFile; @@ -18,6 +25,34 @@ class TranslatableApp { private array $ignoreFiles = []; private string $translationsPath; private TranslationTool $tool; + /** @var array> lines of each generated file: source file relative to the working directory, its line and the language of its strings */ + private array $fakeFileSources = []; + /** @var array>> line of each Vue template string by file, with the lines getTranslatorHintWithVueSource() reads its comment from: the line above the call and the rest of the line from the call */ + private array $vueTemplateLines = []; + /** @var array> lines by file whose TRANSLATORS comment getTranslatorHintWithVueSource() gives to a template string on the next line */ + private array $vueCommentLines = []; + /** @var array hints that getTranslatorHintWithVueSource() writes for Vue strings without a TRANSLATORS comment, which only name the source */ + private array $generatedVueHints = []; + /** Start of a comment xgettext reads: // not after a : or a quote as in URLs, and # between whitespace, unlike #000 or #[Attribute] */ + private const LINE_COMMENT_MARKER = '(?).)*?' . self::TRANSLATORS_INSIDE . ')/ism'; + private const WHOLE_LINE_COMMENT = '/^\s*' . self::COMMENT_START . '/'; + /** Name of a translation function, also as a method like $l->t() */ + private const TRANSLATION_FUNCTION = '\b(?:t|n|_|_n)'; + /** Code that ends a translation call: a call closed on the line, or a line that closes a call over several lines */ + private const ENDED_CALL = '/' . self::TRANSLATION_FUNCTION . '\s*(?\((?:[^()]++|(?&arguments))*\))|^\s*[)\]}]/'; + /** A colon or another translation joined to a translation call, or a colon right after a Vue mustache or PHP template tag */ + private const TEXT_OUTSIDE = '/\)\s*[.+]\s*(?:([\'"])\s*:|(?:([\'"])[^\'"]*\2\s*[.+]\s*)?[\w$>.-]*' . self::TRANSLATION_FUNCTION . '\s*\()|\}\}\s*:|\?>\s*:/'; + /** @var array> lines of the source files read for the lint, by file relative to the working directory */ + private array $sourceFileLines = []; public function __construct(string $appPath, string $translationsPath, TranslationTool $tool) { $this->appPath = $appPath; @@ -48,7 +83,7 @@ public function __construct(string $appPath, string $translationsPath, Translati } public function createOrCheckPotFile(bool $checkFiles = false): void { - $pathToPotFile = $this->translationsPath . '/templates/' . $this->name . '.pot'; + $pathToPotFile = $this->potFile(); // Gather required data $this->createFakeFileForAppInfo(); @@ -64,24 +99,6 @@ public function createOrCheckPotFile(bool $checkFiles = false): void { foreach ($translatableFiles as $entry) { $output = '--output=' . escapeshellarg($pathToPotFile); - $keywords = ''; - if (substr($entry, -4) === '.php') { - $keywords = '--keyword=t --keyword=n:1,2'; - } elseif (substr($entry, -3) === '.py') { - $keywords = '--keyword=_ --keyword=_n:1,2'; - } else { - $keywords = '--keyword=t:2 --keyword=n:2,3'; - } - - $language = '--language='; - if (substr($entry, -4) === '.php') { - $language .= 'PHP'; - } elseif (substr($entry, -3) === '.py') { - $language .= 'Python'; - } else { - $language .= 'Javascript'; - } - $joinexisting = ''; if (file_exists($pathToPotFile)) { $joinexisting = '--join-existing'; @@ -98,7 +115,7 @@ public function createOrCheckPotFile(bool $checkFiles = false): void { $skipErrors = '2>/dev/null'; } - $xgetCmd = 'xgettext ' . $output . ' ' . $joinexisting . ' ' . $keywords . ' ' . $language . ' ' . escapeshellarg($entry) . ' ' . $additionalArguments . ' ' . $extractAll . ' ' . $skipErrors; + $xgetCmd = 'xgettext ' . $output . ' ' . $joinexisting . ' ' . self::XGETTEXT_ARGUMENTS[$this->languageOf($entry)] . ' ' . escapeshellarg($entry) . ' ' . $additionalArguments . ' ' . $extractAll . ' ' . $skipErrors; $this->tool->log($xgetCmd); exec($xgetCmd); @@ -116,7 +133,7 @@ public function createOrCheckPotFile(bool $checkFiles = false): void { } private function checkMissingTranslations(string $entry, string $tmpfname): void { - $translations = (new Gettext\Loader\PoLoader())->loadFile($tmpfname); + $translations = $this->loadPoFile($tmpfname); $first = true; foreach($translations as $translation) { if (preg_match_all('/(^|[^a-zA-Z_]+)(t\([^\)]*\))/', $translation->getOriginal(), $matches)) { @@ -198,6 +215,17 @@ private function loadPoFile(string $poFile): Gettext\Translations { if ($content === null) { throw new RuntimeException('Could not remove the obsolete entries of ' . $poFile . ': ' . preg_last_error_msg()); } + // xgettext wraps a file name with spaces in Unicode isolation characters, which PoLoader would split at the spaces + if (str_contains($content, "\u{2068}")) { + $content = preg_replace_callback('/^#:.*$/m', static fn (array $reference): string => preg_replace_callback( + "/\u{2068}(.*?)\u{2069}/", + static fn (array $file): string => "\u{2068}" . rawurlencode($file[1]) . "\u{2069}", + $reference[0], + ) ?? $reference[0], $content); + if ($content === null) { + throw new RuntimeException('Could not read the references of ' . $poFile . ': ' . preg_last_error_msg()); + } + } return (new Gettext\Loader\PoLoader())->loadString($content); } @@ -294,18 +322,25 @@ private function createFakeFileForAppInfo() { } $strings = []; + $sourceLines = []; + $navigationNames = []; + $add = function (string $string, SimpleXMLElement $node) use (&$strings, &$sourceLines): void { + $strings[] = $string; + $sourceLines[] = $node->getName() === '' || !function_exists('dom_import_simplexml') ? null : dom_import_simplexml($node)->getLineNo(); + }; $xml = simplexml_load_string(file_get_contents($entryName)); if ($xml->name) { - $strings[] = $xml->name->__toString(); + $add($xml->name->__toString(), $xml->name); } if ($xml->navigations) { foreach ($xml->navigations as $navigation) { $name = $navigation->navigation->name->__toString(); if (!in_array($name, $strings)) { - $strings[] = $name; + $add($name, $navigation->navigation->name); } + $navigationNames[] = $name; } } @@ -313,16 +348,16 @@ private function createFakeFileForAppInfo() { if ($xml->name->count() > 1) { foreach ($xml->name as $name) { if ((string)$name->attributes()->lang === 'en') { - $name = $name->__toString(); - if (!in_array($name, $strings)) { - $strings[] = $name; + $text = $name->__toString(); + if (!in_array($text, $strings)) { + $add($text, $name); } } } } else { $name = $xml->name->__toString(); if (!in_array($name, $strings)) { - $strings[] = $name; + $add($name, $xml->name); } } } @@ -333,14 +368,14 @@ private function createFakeFileForAppInfo() { if ((string)$summary->attributes()->lang === 'en') { $name = $summary->__toString(); if (!in_array($name, $strings)) { - $strings[] = $name; + $add($name, $summary); } } } } else { $name = $xml->summary->__toString(); if (!in_array($name, $strings)) { - $strings[] = $name; + $add($name, $xml->summary); } } } @@ -351,21 +386,26 @@ private function createFakeFileForAppInfo() { if ((string)$description->attributes()->lang === 'en') { $name = $description->__toString(); if (!in_array($name, $strings)) { - $strings[] = trim($name); + $add(trim($name), $description); } } } } else { $name = $xml->description->__toString(); if (!in_array($name, $strings)) { - $strings[] = trim($name); + $add(trim($name), $xml->description); } } } - $content = 't(' . $this->escape($string) . ');' . PHP_EOL; + $content = ''; + $line = 1; + $this->appendToFakeFile($this->fakeAppInfoFile, $content, $line, 'relativePath($entryName); + foreach ($strings as $index => $string) { + // Nextcloud formats only the navigation names with vsprintf(), it shows the other texts as they are + $language = in_array($string, $navigationNames, true) ? 'php' : 'other'; + $this->appendToFakeFile($this->fakeAppInfoFile, $content, $line, '$l->t(' . $this->escape($string) . ');' . PHP_EOL, $relativeEntryName, $sourceLines[$index], $language); } file_put_contents($this->fakeAppInfoFile, $content); @@ -373,6 +413,10 @@ private function createFakeFileForAppInfo() { private function createFakeFileForVueFiles(): void { $fakeFileContent = ''; + $fakeFileLine = 1; + $append = function (string $text, ?string $sourceFile = null, ?int $sourceLine = null) use (&$fakeFileContent, &$fakeFileLine): void { + $this->appendToFakeFile($this->fakeVueFile, $fakeFileContent, $fakeFileLine, $text, $sourceFile, $sourceLine, 'script'); + }; foreach ($this->findTranslatableFiles(['.vue']) as $vueFile) { $vueSource = file_get_contents($vueFile); @@ -380,41 +424,52 @@ private function createFakeFileForVueFiles(): void { echo 'Warning: could not read ' . $vueFile . PHP_EOL; continue; } + $relativeVuePath = $this->relativePath($vueFile); $matches = []; - if (preg_match_all('/]*>(.+)<\/script>/sU', $vueSource, $matches, PREG_PATTERN_ORDER)) { - $fakeFileContent .= implode('', $matches[1]) . ";\n"; + if (preg_match_all('/]*>(.+)<\/script>/sU', $vueSource, $matches, PREG_OFFSET_CAPTURE)) { + foreach ($matches[1] as [$script, $offset]) { + $append($script, $relativeVuePath, $this->lineNumber($vueSource, $offset)); + } + $append(";\n"); } if (preg_match('/