Skip to content

Migrate to gettext/gettext v5 - #522

Merged
swissspidy merged 14 commits into
mainfrom
claude/adoring-turing-ad2hq2
Nov 24, 2026
Merged

swissspidy merged 14 commits into
mainfrom
claude/adoring-turing-ad2hq2

Conversation

@swissspidy

@swissspidy swissspidy commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Updates gettext/gettext from ^4.8 to ^5.7.4 and uses gettext/php-scanner (^2.1) to find translatable strings in PHP code.

Previously: #443, #465. See #303.

Why this is more than a version bump

v5 is a different library in a few ways that matter here:

  1. Pieces moved out of the core package. The extractors, the Jed and PHP array generators and the PHP functions scanner are no longer part of gettext/gettext. The PHP scanner now lives in gettext/php-scanner, see "PHP scanning" below.
  2. It normalizes data on write. Headers and flags are sorted alphabetically and references are grouped by file. This PR adopts that, see "Behavior changes".
  3. Versions before 5.7.4 treated "0" as an empty string, dropping msgid "0" entries and msgstr "0" translations. WordPress core has strings like this (_x( '1', 'start of week' ), which translators answer with 0). Fixed upstream in Treat "0" as a valid string php-gettext/Gettext#311, released in 5.7.4, which is why that is the minimum version.

What changed

  • PO and POT files are loaded with the library's PoLoader via Translations::fromPoFiles(). Entries that appear more than once in a file are still merged, as before.
  • make-mo uses the library's MoGenerator, and update-po uses its PoGenerator.
  • PotGenerator keeps its own output format, because POT files need empty msgstr[0] and msgstr[1] lines for plurals, which the library's generator only writes when there is a Plural-Forms header.
  • Translations extends the v5 class and sets the default headers v4 used to set.
  • PHP function calls are found with gettext/php-scanner, which uses nikic/php-parser. PhpFunctionsScanner is a small subclass that recovers from syntax errors, so that a file with an error is still scanned instead of skipped. PhpCodeExtractor maps the calls to the WordPress function signatures, as before.
  • Extractors are standalone classes. Their static fromString() / fromFile() / fromDirectory() API is unchanged, fromStringMultiple() is gone. JedGenerator and PhpArrayGenerator no longer have a library parent.
  • update-po and make-pot --merge / --subtract-and-merge implement their merge rules on top of the v5 API, since v5 replaced v4's merge flags.
  • stubs/Gettext.stub is removed, it only described v4 classes.

This is a breaking change for anyone using these classes as a library: type hints now refer to WP_CLI\I18n\Translations and Gettext\Translation, v4 methods such as Translations::fromPoFile() no longer exist, PhpFunctionsScanner has the API of the gettext/php-scanner class it extends and returns Gettext\Scanner\ParsedFunction objects, and WP_CLI\I18n\ParsedFunction is gone. The unused constants extractor option is gone.

PHP scanning

Upstream changes, released in gettext/php-scanner 2.1.0, made it usable here:

Two things are kept from the old scanner: only the translator comment closest to a call is extracted, and the lines of a multiline comment are joined with spaces.

Compared with the old token-based scanner on WordPress core (trunk), Twenty* themes and Gutenberg (make-pot, PHP only), all strings and references are the same. Some translator comments differ:

  • Fewer wrong comments. The old scanner gave a comment to every call on the same or the next line, so _x( 'F Y', … ) inside printf( __( 'Monthly Archives: %s' ), … ) got translators: %s: Date., and __( 'Latest' ) got the comment meant for Update to %s. Six such comments are gone in core.
  • Comments before ? or : in a ternary are not found, because the parser does not attach them to a node (class-wp-object-cache.php, blocks/gallery.php). WordPress/wordpress-develop and WordPress/gutenberg changes that move these comments are proposed separately.
  • Only the first call after a comment gets it, so in array( _x( 'Most Used', 'tags' ), _x( 'Most Used', 'categories' ) ) the second call has no comment, and neither has %sX-Small / %sX-Large in class-wp-theme-json.php.

Behavior changes

Ordering. This follows what v5 does by default. It does not change the meaning of a file, but existing files change once when they are regenerated:

  • Headers are sorted alphabetically, so Project-Id-Version is no longer first. This applies to POT and PO files and to the header entry inside MO files.
  • References in POT and PO files are grouped by file. This affects strings whose file is referenced again after another file, mostly in projects that ship .js.map files.
  • Flags are sorted, so php-format,js-format becomes js-format,php-format.

JSON and PHP (.l10n.php) output is not affected.

Translator comments in PHP files, see "PHP scanning".

update-po:

  • Obsolete (#~) entries whose string is back in the POT file are reactivated, as msgmerge does. Before, they stayed obsolete and their translation unused.
  • With --no-purge, entries that are no longer in the POT file are now marked as obsolete (#~), as the option's description says. Before, they were kept as active entries.
  • The #, fuzzy flag of the header entry and #| previous strings are kept. Before, they were dropped.
  • With --no-purge, file-level comments are followed by an empty # line, as the library writes them. By default they are still removed.
  • It stops with an error if the POT file cannot be read, instead of treating it as empty.

Fixes:

  • A PO file that consists only of a header entry and has no trailing newline now has its headers read. v4 ignored them.
  • PHP strings with \u{...} escapes no longer trigger a hexdec() deprecation.
  • PHP strings in heredoc and nowdoc syntax without variables are now extracted.

Verification

  • Behat scenarios and unit tests cover "0" strings and translations, the new ordering, duplicate entries, loading several files, file-level comments and flags, obsolete and multiline obsolete entries in update-po, an unreadable POT file, MO output, and PHP scanning including syntax errors and multiline comments.
  • Earlier in this PR, before adopting the v5 ordering, the library's loader and generators and gettext/php-scanner, I compared this branch against main (gettext v4) by running both on the same input and diffing the results byte for byte, with dates normalized. Everything was identical then on: make-pot and audit on Akismet, Contact Form 7, Yoast SEO, WooCommerce, Jetpack, Gutenberg, Twenty Twenty-One, Twenty Twenty-Five, Sage (Blade) and WordPress core (with --subtract, --subtract-and-merge, --merge, --headers, --file-comment); make-mo, make-php, make-json on WordPress and WooCommerce language packs; and update-po on Yoast SEO language packs. Output now differs by the changes listed above.

🤖 Generated with Claude Code

https://claude.ai/code/session_01UWTd5qmztfFv37ybV4xsjV

Summary by CodeRabbit

  • Bug Fixes
    • Corrected handling of translations valued "0" across MO, PHP, and POT generation, and PO updates.
    • Improved preservation and merging of translation metadata, including headers, comments, flags, and source references.
    • Updated PO file merging to better handle duplicate entries and obsolete translations.
  • New Features
    • Added PHP string extraction coverage for function arguments, translator comments, plurals, and source references.
  • Chores
    • Updated the gettext library version.

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

The change updates the gettext dependency and replaces inherited gettext collection, scanner, extractor, and generator behavior with local APIs. Commands use the updated APIs to load, merge, audit, and generate PO, POT, MO, PHP, and JSON output. New tests cover zero-valued translations and merge and update cases.

Changes: Gettext API migration

Layer / File(s) Summary
Translation model and loading
composer.json, .gitattributes, phpstan.neon.dist, stubs/Gettext.stub, src/Translations.php, tests/TranslationsTest.php
Translations adds default headers, PO/POT loading, insertion, reference-list conversion, and value checks. The gettext dependency constraint changes, and the stub file and its PHPStan configuration entry are removed. Tests cover loading, merging, metadata, and MO output.
Scanner APIs
src/ParsedComment.php, src/ParsedFunction.php, src/PhpFunctionsScanner.php, src/JsFunctionsScanner.php, tests/PhpFunctionsScannerTest.php, tests/JsFunctionsScannerTest.php, phpcs.xml.dist
PHP and JavaScript scanners implement parsing and attach translations, references, flags, and comments through the updated APIs. New parsed-data classes support PHP scanning. Scanner tests cover extraction, comments, and string conversion.
Extractor integration
src/*CodeExtractor.php, src/BladeGettextExtractor.php, src/BlockExtractor.php, src/IterableCodeExtractor.php, src/JsonSchemaExtractor.php, src/JsStringFilterTrait.php, tests/BladeGettextExtractorTest.php
Extractors no longer rely on the replaced Gettext extractor base classes. They call local scanners or add translations and references through collection APIs. Blade tests use the local Translations factory.
Generators and output commands
src/Generator.php, src/JedGenerator.php, src/PhpArrayGenerator.php, src/PotGenerator.php, src/MakeJsonCommand.php, src/MakeMoCommand.php, src/MakePhpCommand.php, tests/PotGeneratorTest.php, features/makemo.feature, features/makephp.feature
A local Generator base supports output generation. The Jed, PHP array, and POT generators use it and updated translation APIs. JSON, MO, and PHP commands use updated loading and generation APIs; tests cover generated output and zero-valued translations.
POT, PO update, and audit workflows
src/AuditCommand.php, src/MakePotCommand.php, src/UpdatePoCommand.php, features/makepot.feature, features/updatepo.feature
Audit, POT extraction, subtraction, and PO update workflows use the updated translation APIs. Feature scenarios cover subtraction, reference and header ordering, zero-valued translations, and purge and no-purge updates.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Refactor

Suggested reviewers: brianhenryie, schlessera, ernilambar

Merge Risk: Moderate · up to 64da9

The migration appears sound, and the earlier update-po obsolete-entry problems are fixed. Two data-integrity gaps remain in update-po. An unreadable source POT can lead to destination PO files being overwritten without their translations. Obsolete multiline entries can be written as malformed PO syntax. Both should be addressed before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Migrate to gettext/gettext v5" matches the main change. The PR updates the gettext/gettext dependency from ^4.8 to ^5.7.4 and ports the code to the v5 APIs (PoLoader, Translations::fromPoFi…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title "Migrate to gettext/gettext v5" matches the main change. The PR updates the gettext/gettext dependency from ^4.8 to ^5.7.4 and ports the code to the v5 APIs (PoLoader, Translations::fromPoFiles(), MoGenerator, PoGenerator). The title is short, specific, and states the primary change.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions github-actions Bot added automated-pr command:i18n Related to 'i18n' command labels Nov 17, 2026
@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.98496% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/IterableCodeExtractor.php 62.50% 9 Missing ⚠️
src/ParsedComment.php 81.25% 6 Missing ⚠️
src/PhpCodeExtractor.php 95.16% 3 Missing ⚠️
src/MakePotCommand.php 93.54% 2 Missing ⚠️
src/PotGenerator.php 95.55% 2 Missing ⚠️
src/JedGenerator.php 88.88% 1 Missing ⚠️
src/PhpFunctionsScanner.php 88.88% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@swissspidy
swissspidy marked this pull request as ready for review November 17, 2026 10:59
@swissspidy
swissspidy requested a review from a team as a code owner November 17, 2026 10:59
Copilot AI balanced review requested due to automatic review settings November 17, 2026 10:59

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

gettext/gettext v5 no longer ships extractors, the Jed and PHP array
generators or the PHP functions scanner, and changes the data model
(immutable merges, nullable getters, sorted headers and flags,
references grouped by file).

To keep the output of all commands unchanged:

* Add `Translation` and `Translations` classes on top of the v5 ones
  that keep headers, flags and references in the order they were added
  and provide the default headers that v4 used to set.
* Add a PO loader and PO/MO generators. The ones in v5 treat "0" as an
  empty string, which drops `msgid "0"` entries and `msgstr "0"`
  translations when reading, merging and writing files.
* Port the PHP functions scanner from v4, as it is no longer part of
  the library.
* Make the extractors and the Jed and PHP array generators standalone
  classes.
* Implement the merge strategies used by `update-po` and
  `make-pot --merge/--subtract-and-merge` on top of the v5 API.

Two intentional fixes on the way: headers of a PO file that only
consists of a header entry without a trailing newline are no longer
ignored, and strings with `\u{...}` escapes no longer trigger a
`hexdec()` deprecation.
Narrow the return types of the `create()` factories, read comments
through `toArray()`, and make numeric ranges explicit.
Drop the classes that kept headers, flags and references in the order
they were added. Headers and flags are now sorted alphabetically and
references are grouped by file, as the library does by default.

The keys in generated PHP files keep their order.
@swissspidy
swissspidy force-pushed the claude/adoring-turing-ad2hq2 branch from ece9bd0 to 4cdfebc Compare November 18, 2026 14:51
5.7.4 treats "0" as a valid string, so the local copies of the PO
loader, the PO and MO generators and the `Translation` subclass are no
longer needed.

* PO and POT files are loaded with the library's loader. Entries that
  appear more than once in a file are still merged.
* `make-mo` uses the library's MO generator.
* `update-po` writes PO files with the library's generator. This keeps
  file-level comments with `--no-purge`, the `#, fuzzy` header flag and
  `#|` previous strings, and reactivates obsolete entries that are back
  in the POT file.
* The POT generator keeps its own output format, as POT files need
  empty `msgstr[0]` and `msgstr[1]` lines for plurals.
Entries that are no longer in the POT file were kept as active entries,
although the option is documented to keep them marked with `#~`.
coderabbitai[bot]

This comment was marked as resolved.

* Stop when the source POT file cannot be read instead of treating it
  as empty, which would remove all entries from the PO files.
* Prefix every line of a multiline obsolete entry with `#~`.
  gettext/gettext writes the continuation lines without it.
* When merging duplicate entries, also treat a `#` line after an entry
  as its end, as the PO loader does.
Replaces the tokenizer-based scanner ported from gettext/gettext 4.x
with the one from gettext/php-scanner, which uses nikic/php-parser.

The subclass only adds error recovery, so that a file with a syntax
error is still scanned instead of being skipped. As before, only the
translator comment closest to a function call is extracted, and the
lines of a multiline comment are joined with spaces.

gettext/php-scanner is required as dev-master until 2.1.0 is released.
@swissspidy swissspidy added this to the 3.0.3 milestone Nov 24, 2026
@swissspidy
swissspidy merged commit fff5e52 into main Nov 24, 2026
64 checks passed
@swissspidy
swissspidy deleted the claude/adoring-turing-ad2hq2 branch November 24, 2026 00:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

automated-pr command:i18n Related to 'i18n' command

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants