Skip to content
Merged
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
69 changes: 69 additions & 0 deletions features/makepot.feature
Original file line number Diff line number Diff line change
Expand Up @@ -2016,6 +2016,75 @@ Feature: Generate a POT file of a WordPress project
msgid "foo-plugin"
"""

Scenario: Only parses JavaScript files that can contain translations
Given an empty foo-plugin directory
And a foo-plugin/foo-plugin.php file:
"""
<?php
/**
* Plugin Name: Foo Plugin
*/
"""
And a foo-plugin/no-calls.js file:
"""
function __webpack_require__( moduleId ) { return moduleId; }
const strings = { label_x: 'Not translated', foo__: 'Not translated either' };
"""
And a foo-plugin/mangled.js file:
"""
Object(i18n[/* __ */ "a"])( 'Mangled webpack', 'foo-plugin' );
"""
And a foo-plugin/eval.js file:
"""
eval( "var a = 1;\n__( 'Inside eval', 'foo-plugin' );" );
"""
And a foo-plugin/minified.js file:
"""
var a=Object(u.__)("Minified","foo-plugin");
"""
And a foo-plugin/comment.js file:
"""
// translators: A comment.
wp.i18n._x( 'With comment', 'context', 'foo-plugin' );
"""

When I try `wp i18n make-pot foo-plugin --debug=make-pot`
Then STDERR should contain:
"""
Skipping file no-calls.js: no translation function calls found
"""
And STDERR should not contain:
"""
Skipping file mangled.js
"""
And STDERR should not contain:
"""
Skipping file eval.js
"""
And the foo-plugin/foo-plugin.pot file should contain:
"""
msgid "Mangled webpack"
"""
And the foo-plugin/foo-plugin.pot file should contain:
"""
msgid "Inside eval"
"""
And the foo-plugin/foo-plugin.pot file should contain:
"""
msgid "Minified"
"""
And the foo-plugin/foo-plugin.pot file should contain:
"""
#. translators: A comment.
#: comment.js:2
msgctxt "context"
msgid "With comment"
"""
And the foo-plugin/foo-plugin.pot file should not contain:
"""
Not translated
"""

Scenario: Ignores dynamic import in JavaScript file.
Given an empty foo-plugin directory
And a foo-plugin/foo-plugin.php file:
Expand Down
65 changes: 64 additions & 1 deletion src/JsFunctionsScanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Gettext\Utils\JsFunctionsScanner as GettextJsFunctionsScanner;
use Gettext\Utils\ParsedComment;
use WP_CLI;
use Peast\Peast;
use Peast\Syntax\Node;
use Peast\Traverser;
Expand Down Expand Up @@ -59,9 +60,21 @@ public function saveGettextFunctions( $translations, array $options ) {
$translations = $translations[0];
}

$functions = isset( $options['functions'] ) && is_array( $options['functions'] ) ? array_keys( $options['functions'] ) : [];

// Parsing is by far the most expensive part, so skip it for code that
// can't contain any translations, and skip collecting comments if
// none of them can matter.
$has_eval = $this->containsName( [ 'eval' ] );
if ( ! $has_eval && ! $this->containsName( $functions ) ) {
$file = isset( $options['file'] ) && is_scalar( $options['file'] ) ? (string) $options['file'] : '';
WP_CLI::debug( "Skipping file {$file}: no translation function calls found", 'make-pot' );
return;
}

$peast_options = [
'sourceType' => Peast::SOURCE_TYPE_MODULE,
'comments' => false !== $this->extract_comments,
'comments' => $has_eval ? false !== $this->extract_comments : $this->needsComments( $functions ),
'jsx' => true,
];
$ast = Peast::latest( $this->code, $peast_options )->parse();
Expand Down Expand Up @@ -286,6 +299,56 @@ function ( $node ) use ( &$translations, $options, $scanner ) {
$traverser->traverse( $ast );
}

/**
* Whether the code contains any of the given names as a whole word.
*
* Every call that resolveExpressionCallee() can resolve contains the
* function name as a whole word: as an identifier (`__(`, `u.__(`,
* `(0, u.__)(`), as a string (`u["__"]`) or as a comment (`u[/* __ *\/ "a"]`).
*
* This doesn't hold for code inside string literals passed to `eval()`,
* as in `eval("\n__(...)")`, so callers must check for `eval` too.
*
* @param array<int|string> $names Names to look for.
* @return bool
*/
private function containsName( array $names ) {
if ( empty( $names ) ) {
return false;
}

$pattern = implode( '|', array_map( 'preg_quote', array_map( 'strval', $names ) ) );

return 1 === preg_match( '/(?<![\w$])(?:' . $pattern . ')(?![\w$])/', $this->code );
}

/**
* Whether the code needs to be parsed with comments.
*
* Comments are needed for translator comments, and for the function names
* in mangled webpack output like `u[/* __ *\/ "a"]( "translation" )`.
*
* Only called for code that contains at least one of the function names.
*
* @param array<int|string> $functions Function names, not empty.
* @return bool
*/
private function needsComments( array $functions ) {
if ( false === $this->extract_comments ) {
return false;
}

foreach ( (array) $this->extract_comments as $prefix ) {
if ( '' === $prefix || false !== strpos( $this->code, $prefix ) ) {
return true;
}
}

$pattern = implode( '|', array_map( 'preg_quote', array_map( 'strval', $functions ) ) );

return 1 === preg_match( '#/\*\s*(?:' . $pattern . ')\s*\*/#', $this->code );
}

/**
* Resolve the callee of a call expression using known formats.
*
Expand Down
67 changes: 67 additions & 0 deletions tests/JsFunctionsScannerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

namespace WP_CLI\I18n\Tests;

use Gettext\Translations;
use WP_CLI\I18n\JsCodeExtractor;
use WP_CLI\Tests\TestCase;

class JsFunctionsScannerTest extends TestCase {

/**
* Helper to extract translations from JavaScript code.
*
* @param string $code JavaScript code.
* @param array<mixed> $options Extraction options.
* @return Translations
*/
private function extract( $code, array $options = [] ) {
$translations = new Translations();

JsCodeExtractor::fromString( $code, $translations, $options + [ 'file' => 'test.js' ] );

return $translations;
}

public function test_does_not_extract_anything_without_functions() {
$translations = $this->extract(
"__( 'Hello', 'foo-plugin' );",
[ 'functions' => [] ]
);

$this->assertCount( 0, $translations );
}

public function test_ignores_comments_if_comment_extraction_is_disabled() {
$translations = $this->extract(
"// translators: A comment.\n__( 'Hello', 'foo-plugin' );",
[ 'extractComments' => false ]
);

$translation = $translations->find( null, 'Hello' );
$this->assertNotFalse( $translation );
$this->assertSame( [], $translation->getExtractedComments() );
}

public function test_extracts_all_comments_with_empty_prefix() {
$translations = $this->extract(
"// Any comment.\n__( 'Hello', 'foo-plugin' );",
[ 'extractComments' => '' ]
);

$translation = $translations->find( null, 'Hello' );
$this->assertNotFalse( $translation );
$this->assertSame( [ 'Any comment.' ], $translation->getExtractedComments() );
}

public function test_extracts_translator_comments_with_prefix() {
$translations = $this->extract(
"// translators: A comment.\n__( 'Hello', 'foo-plugin' );",
[ 'extractComments' => [ 'translators', 'Translators' ] ]
);

$translation = $translations->find( null, 'Hello' );
$this->assertNotFalse( $translation );
$this->assertSame( [ 'translators: A comment.' ], $translation->getExtractedComments() );
}
}
Loading