Skip to content

Commit d47a013

Browse files
authored
Skip parsing JavaScript that can't contain translations (#509)
1 parent 24380c5 commit d47a013

3 files changed

Lines changed: 200 additions & 1 deletion

File tree

‎features/makepot.feature‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2016,6 +2016,75 @@ Feature: Generate a POT file of a WordPress project
20162016
msgid "foo-plugin"
20172017
"""
20182018

2019+
Scenario: Only parses JavaScript files that can contain translations
2020+
Given an empty foo-plugin directory
2021+
And a foo-plugin/foo-plugin.php file:
2022+
"""
2023+
<?php
2024+
/**
2025+
* Plugin Name: Foo Plugin
2026+
*/
2027+
"""
2028+
And a foo-plugin/no-calls.js file:
2029+
"""
2030+
function __webpack_require__( moduleId ) { return moduleId; }
2031+
const strings = { label_x: 'Not translated', foo__: 'Not translated either' };
2032+
"""
2033+
And a foo-plugin/mangled.js file:
2034+
"""
2035+
Object(i18n[/* __ */ "a"])( 'Mangled webpack', 'foo-plugin' );
2036+
"""
2037+
And a foo-plugin/eval.js file:
2038+
"""
2039+
eval( "var a = 1;\n__( 'Inside eval', 'foo-plugin' );" );
2040+
"""
2041+
And a foo-plugin/minified.js file:
2042+
"""
2043+
var a=Object(u.__)("Minified","foo-plugin");
2044+
"""
2045+
And a foo-plugin/comment.js file:
2046+
"""
2047+
// translators: A comment.
2048+
wp.i18n._x( 'With comment', 'context', 'foo-plugin' );
2049+
"""
2050+
2051+
When I try `wp i18n make-pot foo-plugin --debug=make-pot`
2052+
Then STDERR should contain:
2053+
"""
2054+
Skipping file no-calls.js: no translation function calls found
2055+
"""
2056+
And STDERR should not contain:
2057+
"""
2058+
Skipping file mangled.js
2059+
"""
2060+
And STDERR should not contain:
2061+
"""
2062+
Skipping file eval.js
2063+
"""
2064+
And the foo-plugin/foo-plugin.pot file should contain:
2065+
"""
2066+
msgid "Mangled webpack"
2067+
"""
2068+
And the foo-plugin/foo-plugin.pot file should contain:
2069+
"""
2070+
msgid "Inside eval"
2071+
"""
2072+
And the foo-plugin/foo-plugin.pot file should contain:
2073+
"""
2074+
msgid "Minified"
2075+
"""
2076+
And the foo-plugin/foo-plugin.pot file should contain:
2077+
"""
2078+
#. translators: A comment.
2079+
#: comment.js:2
2080+
msgctxt "context"
2081+
msgid "With comment"
2082+
"""
2083+
And the foo-plugin/foo-plugin.pot file should not contain:
2084+
"""
2085+
Not translated
2086+
"""
2087+
20192088
Scenario: Ignores dynamic import in JavaScript file.
20202089
Given an empty foo-plugin directory
20212090
And a foo-plugin/foo-plugin.php file:

‎src/JsFunctionsScanner.php‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Gettext\Utils\JsFunctionsScanner as GettextJsFunctionsScanner;
66
use Gettext\Utils\ParsedComment;
7+
use WP_CLI;
78
use Peast\Peast;
89
use Peast\Syntax\Node;
910
use Peast\Traverser;
@@ -59,9 +60,21 @@ public function saveGettextFunctions( $translations, array $options ) {
5960
$translations = $translations[0];
6061
}
6162

63+
$functions = isset( $options['functions'] ) && is_array( $options['functions'] ) ? array_keys( $options['functions'] ) : [];
64+
65+
// Parsing is by far the most expensive part, so skip it for code that
66+
// can't contain any translations, and skip collecting comments if
67+
// none of them can matter.
68+
$has_eval = $this->containsName( [ 'eval' ] );
69+
if ( ! $has_eval && ! $this->containsName( $functions ) ) {
70+
$file = isset( $options['file'] ) && is_scalar( $options['file'] ) ? (string) $options['file'] : '';
71+
WP_CLI::debug( "Skipping file {$file}: no translation function calls found", 'make-pot' );
72+
return;
73+
}
74+
6275
$peast_options = [
6376
'sourceType' => Peast::SOURCE_TYPE_MODULE,
64-
'comments' => false !== $this->extract_comments,
77+
'comments' => $has_eval ? false !== $this->extract_comments : $this->needsComments( $functions ),
6578
'jsx' => true,
6679
];
6780
$ast = Peast::latest( $this->code, $peast_options )->parse();
@@ -286,6 +299,56 @@ function ( $node ) use ( &$translations, $options, $scanner ) {
286299
$traverser->traverse( $ast );
287300
}
288301

302+
/**
303+
* Whether the code contains any of the given names as a whole word.
304+
*
305+
* Every call that resolveExpressionCallee() can resolve contains the
306+
* function name as a whole word: as an identifier (`__(`, `u.__(`,
307+
* `(0, u.__)(`), as a string (`u["__"]`) or as a comment (`u[/* __ *\/ "a"]`).
308+
*
309+
* This doesn't hold for code inside string literals passed to `eval()`,
310+
* as in `eval("\n__(...)")`, so callers must check for `eval` too.
311+
*
312+
* @param array<int|string> $names Names to look for.
313+
* @return bool
314+
*/
315+
private function containsName( array $names ) {
316+
if ( empty( $names ) ) {
317+
return false;
318+
}
319+
320+
$pattern = implode( '|', array_map( 'preg_quote', array_map( 'strval', $names ) ) );
321+
322+
return 1 === preg_match( '/(?<![\w$])(?:' . $pattern . ')(?![\w$])/', $this->code );
323+
}
324+
325+
/**
326+
* Whether the code needs to be parsed with comments.
327+
*
328+
* Comments are needed for translator comments, and for the function names
329+
* in mangled webpack output like `u[/* __ *\/ "a"]( "translation" )`.
330+
*
331+
* Only called for code that contains at least one of the function names.
332+
*
333+
* @param array<int|string> $functions Function names, not empty.
334+
* @return bool
335+
*/
336+
private function needsComments( array $functions ) {
337+
if ( false === $this->extract_comments ) {
338+
return false;
339+
}
340+
341+
foreach ( (array) $this->extract_comments as $prefix ) {
342+
if ( '' === $prefix || false !== strpos( $this->code, $prefix ) ) {
343+
return true;
344+
}
345+
}
346+
347+
$pattern = implode( '|', array_map( 'preg_quote', array_map( 'strval', $functions ) ) );
348+
349+
return 1 === preg_match( '#/\*\s*(?:' . $pattern . ')\s*\*/#', $this->code );
350+
}
351+
289352
/**
290353
* Resolve the callee of a call expression using known formats.
291354
*

‎tests/JsFunctionsScannerTest.php‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
3+
namespace WP_CLI\I18n\Tests;
4+
5+
use Gettext\Translations;
6+
use WP_CLI\I18n\JsCodeExtractor;
7+
use WP_CLI\Tests\TestCase;
8+
9+
class JsFunctionsScannerTest extends TestCase {
10+
11+
/**
12+
* Helper to extract translations from JavaScript code.
13+
*
14+
* @param string $code JavaScript code.
15+
* @param array<mixed> $options Extraction options.
16+
* @return Translations
17+
*/
18+
private function extract( $code, array $options = [] ) {
19+
$translations = new Translations();
20+
21+
JsCodeExtractor::fromString( $code, $translations, $options + [ 'file' => 'test.js' ] );
22+
23+
return $translations;
24+
}
25+
26+
public function test_does_not_extract_anything_without_functions() {
27+
$translations = $this->extract(
28+
"__( 'Hello', 'foo-plugin' );",
29+
[ 'functions' => [] ]
30+
);
31+
32+
$this->assertCount( 0, $translations );
33+
}
34+
35+
public function test_ignores_comments_if_comment_extraction_is_disabled() {
36+
$translations = $this->extract(
37+
"// translators: A comment.\n__( 'Hello', 'foo-plugin' );",
38+
[ 'extractComments' => false ]
39+
);
40+
41+
$translation = $translations->find( null, 'Hello' );
42+
$this->assertNotFalse( $translation );
43+
$this->assertSame( [], $translation->getExtractedComments() );
44+
}
45+
46+
public function test_extracts_all_comments_with_empty_prefix() {
47+
$translations = $this->extract(
48+
"// Any comment.\n__( 'Hello', 'foo-plugin' );",
49+
[ 'extractComments' => '' ]
50+
);
51+
52+
$translation = $translations->find( null, 'Hello' );
53+
$this->assertNotFalse( $translation );
54+
$this->assertSame( [ 'Any comment.' ], $translation->getExtractedComments() );
55+
}
56+
57+
public function test_extracts_translator_comments_with_prefix() {
58+
$translations = $this->extract(
59+
"// translators: A comment.\n__( 'Hello', 'foo-plugin' );",
60+
[ 'extractComments' => [ 'translators', 'Translators' ] ]
61+
);
62+
63+
$translation = $translations->find( null, 'Hello' );
64+
$this->assertNotFalse( $translation );
65+
$this->assertSame( [ 'translators: A comment.' ], $translation->getExtractedComments() );
66+
}
67+
}

0 commit comments

Comments
 (0)