Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 117 additions & 100 deletions translations/translationtool/src/translationtool.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,20 @@ class TranslatableApp {
private TranslationTool $tool;
/** @var array<string, array<int, array{0: string, 1: ?int, 2: 'php'|'python'|'script'|'other'}>> 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<string, array<int, list<string>>> 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 */
/** @var array<string, array<int, list<string>>> line of each Vue template string by file, with the lines createFakeFileForVueFiles() reads its comment from: the line above the call and the rest of the line from the call */
private array $vueTemplateLines = [];
/** @var array<string, array<int, true>> lines by file whose TRANSLATORS comment getTranslatorHintWithVueSource() gives to a template string on the next line */
/** @var array<string, array<int, true>> lines by file whose TRANSLATORS comment createFakeFileForVueFiles() gives to a template string on the next line */
private array $vueCommentLines = [];
/** @var array<string, true> hints that getTranslatorHintWithVueSource() writes for Vue strings without a TRANSLATORS comment, which only name the source */
/** @var array<string, true> hints that createFakeFileForVueFiles() writes for Vue strings without a TRANSLATORS comment, which only name the source */
private array $generatedVueHints = [];
/** A JavaScript string literal in single quotes, double quotes or backticks, possessive so a long text doesn't exhaust PCRE's stack */
private const VUE_LITERAL = '(?:\'(?:[^\'\\\\]++|\\\\.)*+\'|"(?:[^"\\\\]++|\\\\.)*+"|`(?:[^`\\\\]++|\\\\.)*+`)';
/** A JavaScript comment */
private const VUE_COMMENT = '(?:\/\*(?:[^*]++|\*(?!\/))*+\*\/|\/\/[^\n]*+)';
/** Whitespace and comments, which JavaScript allows between the tokens of a call */
private const VUE_SPACE = '(?:\s++|' . self::VUE_COMMENT . ')*+';
/** A text of a Vue template call: string literals joined with + */
private const VUE_TEXT = '(' . self::VUE_LITERAL . '(?:' . self::VUE_SPACE . '\+' . self::VUE_SPACE . self::VUE_LITERAL . ')*+)';
/** 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 = '(?<![:"\'])\/\/|(?<!\S)#(?!\S)';
private const BLOCK_COMMENT_MARKER = '\/\*';
Expand Down Expand Up @@ -91,17 +99,17 @@ public function __construct(string $appPath, string $translationsPath, Translati
public function createOrCheckPotFile(bool $checkFiles = false): void {
$pathToPotFile = $this->potFile();

// Gather required data
$this->createFakeFileForAppInfo();
$this->createFakeFileForVueFiles();
$this->createFakeFileForLocale();
$translatableFiles = $this->findTranslatableFiles(
['.php', '.js', '.jsx', '.mjs', '.html', '.ts', '.tsx', '.py'],
['.min.js']
);

// Let gettext create the pot file
try {
// Gather required data
$this->createFakeFileForAppInfo();
$this->createFakeFileForVueFiles();
$this->createFakeFileForLocale();
$translatableFiles = $this->findTranslatableFiles(
['.php', '.js', '.jsx', '.mjs', '.html', '.ts', '.tsx', '.py'],
['.min.js']
);

// Let gettext create the pot file
$this->extractTranslatableFiles($translatableFiles, $pathToPotFile, $checkFiles);
} finally {
// Don't forget to remove the temporary file
Expand All @@ -118,13 +126,16 @@ private function extractTranslatableFiles(array $translatableFiles, string $path
if ($checkFiles) {
foreach ($translatableFiles as $entry) {
$tmpfname = $this->temporaryFile('checkpot');
// extract-all generates a recurrent warning
if ($this->extractStrings([$entry], $tmpfname, false, '--extract-all 2>/dev/null')) {
$this->checkMissingTranslations($entry, $tmpfname);
} else {
echo 'Warning: could not extract the strings of ' . $entry . PHP_EOL;
try {
// extract-all generates a recurrent warning
if ($this->extractStrings([$entry], $tmpfname, false, '--extract-all 2>/dev/null')) {
$this->checkMissingTranslations($entry, $tmpfname);
} else {
echo 'Warning: could not extract the strings of ' . $entry . PHP_EOL;
}
} finally {
unlink($tmpfname);
}
unlink($tmpfname);
}
} else {
// One call per run of files in the same language keeps the order of the pot file without rewriting it for every file
Expand Down Expand Up @@ -511,49 +522,79 @@ private function createFakeFileForVueFiles(): void {
$relativeVuePath = $this->relativePath($vueFile);

$matches = [];
if (preg_match_all('/<script[^>]*>(.+)<\/script>/sU', $vueSource, $matches, PREG_OFFSET_CAPTURE)) {
$scripts = preg_match_all('/<script[^>]*>(.+)<\/script>/sU', $vueSource, $matches, PREG_OFFSET_CAPTURE);
if ($scripts === false) {
throw $this->vuePatternFailure($vueFile);
}
if ($scripts > 0) {
foreach ($matches[1] as [$script, $offset]) {
$append($script, $relativeVuePath, $this->lineNumber($vueSource, $offset));
}
$append(";\n");
}

if (preg_match('/<template>(.+)<\/template>/s', $vueSource, $matches, PREG_OFFSET_CAPTURE)) {
$hasTemplate = preg_match('/<template>(.+)<\/template>/s', $vueSource, $matches, PREG_OFFSET_CAPTURE);
if ($hasTemplate === false) {
throw $this->vuePatternFailure($vueFile);
}
if ($hasTemplate === 1) {
// Also parse the template but make sure we keep the correct line numbers for source references
$vueSource = str_repeat("\n", substr_count($vueSource, "\n", 0, $matches[1][1]));
$vueSource .= $matches[1][0];
$templateLines = explode("\n", $vueSource);
// The match starts with the character before t(, so a call at the start of a line takes its comment from the line before
$appendTemplateCall = function (array $callMatch, string $code) use ($append, $vueFile, $vueSource, $templateLines, $relativeVuePath): void {
[$call, $offset] = $callMatch;
$sourceLine = $this->lineNumber($vueSource, $offset + 1);
$this->vueTemplateLines[$relativeVuePath][$sourceLine] = [
$templateLines[$this->lineNumber($vueSource, $offset) - 2] ?? '',
explode("\n", substr($vueSource, $offset), 2)[0],
];
$append($this->getTranslatorHintWithVueSource($vueFile, $vueSource, $call));
$append($code . PHP_EOL, $relativeVuePath, $sourceLine);
};

// t
preg_match_all("/\Wt\s*\(\s*'?([\w.]+)'?,\s*'(.+)'\s*[),]/", $vueSource, $singleQuoteMatches, PREG_OFFSET_CAPTURE);
preg_match_all("/\Wt\s*\(\s*\"?([\w.]+)\"?,\s*\"(.+)\"\s*[),]/", $vueSource, $doubleQuoteMatches, PREG_OFFSET_CAPTURE);
preg_match_all("/\Wt\s*\(\s*'?([\w.]+)'?\s*,\s*`(.+)`\s*[),]/msU", $vueSource, $templateQuoteMatches, PREG_OFFSET_CAPTURE);
$matches0 = array_merge($singleQuoteMatches[0], $doubleQuoteMatches[0], $templateQuoteMatches[0]);
$matches2 = array_merge($singleQuoteMatches[2], $doubleQuoteMatches[2], $templateQuoteMatches[2]);
foreach (array_keys($matches2) as $k) {
$appendTemplateCall($matches0[$k], "t('" . $this->name . "', '" . preg_replace('/\s+/', ' ', $matches2[$k][0]) . "');");
$hintPath = substr($vueFile, strpos($vueFile, $this->name . '/src/') + strlen($this->name . '/'));
$calls = [];
$firstOffsets = [];
foreach (['t' => 1, 'n' => 2] as $function => $textCount) {
// Grouped by the quotes of the first text, which keeps the order of the existing strings in the POT
foreach (["'", '"', '`'] as $quote) {
// Like xgettext, the last text ends before a + that isn't followed by a string. The ), , or + after it isn't
// part of the match, so a call right after it is found too.
$comma = self::VUE_SPACE . ',' . self::VUE_SPACE;
$pattern = '/\W' . $function . self::VUE_SPACE . '\(' . self::VUE_SPACE . '[\'"`]?[\w.]+[\'"`]?' . $comma . '(?=' . $quote . ')'
. implode($comma, array_fill(0, $textCount, self::VUE_TEXT)) . self::VUE_SPACE . '(?=[),+])/s';
if (preg_match_all($pattern, $vueSource, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE) === false) {
throw $this->vuePatternFailure($vueFile);
}
foreach ($matches as $match) {
$texts = array_map(fn (array $group): string => $this->vueText($group[0]), array_slice($match, 1));
if ($texts[0] === '') {
continue;
}
$offset = $match[0][1];
$sourceLine = $this->lineNumber($vueSource, $offset + 1);
$calls[] = [$offset, $sourceLine, $function . "('" . $this->name . "', '" . implode("', '", $texts) . "');"];
$firstOffsets[$sourceLine] = min($firstOffsets[$sourceLine] ?? $offset, $offset);
}
}
}

// n
preg_match_all("/\Wn\s*\(\s*'?([\w.]+)'?,\s*'(.+)'\s*,\s*'(.+)'\s*(.+)\s*[),]/", $vueSource, $singleQuoteMatches, PREG_OFFSET_CAPTURE);
preg_match_all("/\Wn\s*\(\s*\"?([\w.]+)\"?,\s*\"(.+)\"\s*,\s*\"(.+)\"\s*(.+)\s*[),]/", $vueSource, $doubleQuoteMatches, PREG_OFFSET_CAPTURE);
preg_match_all("/\Wn\s*\(\s*'?([\w.]+)'?\s*,\s*`(.+)`\s*,\s*`(.+)`\s*[),]/msU", $vueSource, $templateQuoteMatches, PREG_OFFSET_CAPTURE);
$matches0 = array_merge($singleQuoteMatches[0], $doubleQuoteMatches[0], $templateQuoteMatches[0]);
$matches2 = array_merge($singleQuoteMatches[2], $doubleQuoteMatches[2], $templateQuoteMatches[2]);
$matches3 = array_merge($singleQuoteMatches[3], $doubleQuoteMatches[3], $templateQuoteMatches[3]);
foreach (array_keys($matches2) as $k) {
$appendTemplateCall($matches0[$k], "n('" . $this->name . "', '" . preg_replace('/\s+/', ' ', $matches2[$k][0]) . "', '" . preg_replace('/\s+/', ' ', $matches3[$k][0]) . "');");
foreach ($calls as [$offset, $sourceLine, $code]) {
$comment = null;
// A TRANSLATORS comment only reaches the first string of a line, as xgettext does with one on the line above
if ($firstOffsets[$sourceLine] === $offset) {
// The match starts with the character before t(, so a call at the start of a line takes its comment from the line before
$line = $this->lineNumber($vueSource, $offset);
$previousLine = $templateLines[$line - 2] ?? '';
$currentLine = explode("\n", substr($vueSource, $offset), 2)[0];
// The lint reads a line like its first string does, whichever call comes first in the generated file
$this->vueTemplateLines[$relativeVuePath][$sourceLine] = [$previousLine, $currentLine];
// A comment in the rest of the line wins, so strings on consecutive lines can each have their own, like
// https://github.com/nextcloud/forms/blob/5c905b36b1ce3ca1848175d39d813581732e159d/src/views/Results.vue#L261-L263
$readsCurrentLine = str_contains($currentLine, 'TRANSLATORS');
$comment = $this->vueTranslatorComment($readsCurrentLine ? $currentLine : $previousLine);
if ($comment !== null && !$readsCurrentLine) {
$this->vueCommentLines[$relativeVuePath][$line - 1] = true;
}
}
if ($comment === null) {
$hint = 'TRANSLATORS ' . $hintPath . ':' . $sourceLine;
$this->generatedVueHints[$hint] = true;
} else {
$hint = str_replace(' ', ' ', 'TRANSLATORS ' . $comment . " ($hintPath:$sourceLine)");
}
$append('// ' . $hint . PHP_EOL);
$append($code . PHP_EOL, $relativeVuePath, $sourceLine);
}
}
}
Expand Down Expand Up @@ -800,7 +841,7 @@ private function languageOf(string $file): string {
/**
* Source lines a comment for the string on $line comes from
*
* In a Vue template, getTranslatorHintWithVueSource() reads the line above the call and the rest of the line from the call on. Everywhere else
* In a Vue template, createFakeFileForVueFiles() reads the line above the call and the rest of the line from the call on. Everywhere else
* xgettext takes the comment that ends on the nearest non-blank line above the string, also a trailing one.
*
* @return array<int, string> the lines by line number, in a Vue template only in their order
Expand Down Expand Up @@ -882,55 +923,31 @@ private function lineNumber(string $content, int $offset): int {
return substr_count($content, "\n", 0, $offset) + 1;
}

private function getTranslatorHintWithVueSource(string $vueFile, string $content, string $translation): string {
$relativeVuePath = substr($vueFile, strpos($vueFile, $this->name . '/src/') + strlen($this->name . '/'));

$position = strpos($content, $translation);
$contentBefore = substr($content, 0, $position);
$contentAfter = substr($content, $position);
$lineNumber = $this->lineNumber($content, $position);

$linesBefore = explode("\n", $contentBefore);
$linesAfter = explode("\n", $contentAfter);
$previousLine = $linesBefore[$lineNumber - 2] ?? '';
$currentLine = $linesAfter[0];

// If we have a translation hint in the current line, we use it
// This prevents mismatching hints if we have two translations
// over consecutive lines
// Like https://github.com/nextcloud/forms/blob/5c905b36b1ce3ca1848175d39d813581732e159d/src/views/Results.vue#L261-L263
$readsCurrentLine = strpos($currentLine, 'TRANSLATORS') !== false;
$searchComment = $readsCurrentLine
? $currentLine
: $previousLine;

// We try to find a comment with the translators hint
// <!-- TRANSLATORS: This is a comment -->
// <!-- TRANSLATORS : This is a comment -->
// <!-- TRANSLATORS This is a comment -->
// t('forms', 'Save to home') // TRANSLATORS: Export the file to the home path
$re = '/TRANSLATORS[: ]*(.*)/m';
preg_match_all($re, $searchComment, $matches, PREG_SET_ORDER, 0);

// If we have a comment, we use it
if (count($matches) > 0 && count($matches[0]) > 1) {
if (!$readsCurrentLine) {
$this->vueCommentLines[$this->relativePath($vueFile)][$lineNumber - 1] = true;
}
// Remove double spaces
$comment = str_replace(' ', ' ', $matches[0][1]);
// Remove leading and trailing spaces
$comment = trim($comment);
// Remove newlines
$comment = str_replace("\n", '', $comment);
// Remove html end comment
$comment = str_replace('-->', '', $comment);
return str_replace(' ', ' ', '// TRANSLATORS ' . $comment . " ($relativeVuePath:$lineNumber)" . PHP_EOL);
}

$hint = 'TRANSLATORS ' . $relativeVuePath . ':' . $lineNumber;
$this->generatedVueHints[$hint] = true;
return '// ' . $hint . PHP_EOL;
/**
* A pattern failed on a Vue file, which would otherwise drop its strings from the POT and so from Transifex
*/
private function vuePatternFailure(string $vueFile): RuntimeException {
return new RuntimeException('Could not read the translations of ' . $vueFile . ': ' . preg_last_error_msg());
}

/**
* The text of string literals joined with +, without the comments between them, as the text of the single-quoted
* literal in the generated file
*/
private function vueText(string $literals): string {
preg_match_all('/' . self::VUE_COMMENT . '(*SKIP)(*FAIL)|' . self::VUE_LITERAL . '/s', $literals, $matches);
$text = implode('', array_map(static fn (string $literal): string => substr($literal, 1, -1), $matches[0]));
return preg_replace(["/\\\\.(*SKIP)(*FAIL)|'/s", '/\s+/'], ["\\'", ' '], $text);
}

/**
* The text of a TRANSLATORS comment on a template line, without the end of the comment and what follows it
*/
private function vueTranslatorComment(string $line): ?string {
if (preg_match('/TRANSLATORS[: ]*(.*)/', $line, $matches) !== 1) {
return null;
}
return preg_replace('/(?:-->|\*\/).*$/s', '', trim(str_replace(' ', ' ', $matches[1])));
}

private function deleteFakeFileForAppInfo(): void {
Expand Down
Loading