Skip to content

Add hook to expose changed files for OPCache invalidation - #501

Merged
swissspidy merged 17 commits into
mainfrom
copilot/fix-opcache-invalidation
Nov 24, 2026
Merged

swissspidy merged 17 commits into
mainfrom
copilot/fix-opcache-invalidation

Conversation

Copilot AI commented Feb 14, 2026 •

Copy link
Copy Markdown
Contributor

WP-CLI runs in CLI SAPI context, so WordPress core's wp_opcache_invalidate_directory() calls during plugin/theme updates don't affect PHP-FPM opcache. Users need the list of changed files to invalidate opcache using external tools like cachetool.

The custom plugin and theme upgraders are updated to hook into wp_opcache_invalidate_file to get that list. Then, it is exposed via a custom WP-CLI hook (WP_CLI::do_hook()) so that other packages such as https://github.com/wearerequired/wp-cli-clear-opcache could be notified of updates and invalidate all the files in PHP-FPM.

Usage:

WP_CLI::add_hook(
	'plugin_update_finished', // or 'theme_update_finished'
	static function ( array $files ) {
		// Absolute paths of the PHP files written by the update.
	}
);

Notes:

  • The hook fires right after the bulk upgrade, before the results are reported, so it also fires when some of the updates failed.
  • WordPress only applies the wp_opcache_invalidate_file filter when opcache_invalidate() is available in the CLI (the OPcache extension is loaded, and opcache.restrict_api allows it). Otherwise the list is empty.
  • It covers wp plugin update and wp theme update. Updates with --version, which go through install --force, don't fire it.

Summary by CodeRabbit

  • New Features
    • Plugin and theme update-finished hooks now include the files changed during an update, helping integrations identify what was updated.
  • Bug Fixes
    • Bulk updates now report a clear error when the filesystem cannot be reached, rather than continuing with an invalid update result.

@github-actions github-actions Bot added command:plugin-update Related to 'plugin update' command scope:testing Related to testing labels Feb 14, 2026
Copilot AI and others added 5 commits February 14, 2026 22:43
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
…logic

Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix opcache invalidation on plugin update Add --show-changed-files flag for opcache invalidation Feb 14, 2026
Copilot AI requested a review from swissspidy February 14, 2026 22:51
@swissspidy swissspidy mentioned this pull request Feb 15, 2026
2 tasks done
@swissspidy swissspidy changed the title Add --show-changed-files flag for opcache invalidation Add hook to expose changed files for OPCache invalidation Mar 10, 2026
@codecov

codecov Bot commented Mar 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.87500% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/WP_CLI/CommandWithUpgrade.php 75.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@swissspidy
swissspidy marked this pull request as ready for review March 11, 2026 07:55
@swissspidy
swissspidy requested a review from a team as a code owner March 11, 2026 07:55
Copilot AI review requested due to automatic review settings March 11, 2026 07:55

This comment was marked as resolved.

@swissspidy swissspidy linked an issue Mar 12, 2026 that may be closed by this pull request
2 tasks done
swissspidy and others added 2 commits November 24, 2026 10:12
Failed updates made `update_many()` exit before the hook was fired, even
though files of the other items had changed. The hook now fires right
after the bulk upgrade, and only when the upgrader tracks changed files,
so that subclasses using another upgrader class keep working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UWTd5pwpi2xQfDA6mUYkkx
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Plugin and theme update commands now use custom upgraders that track changed file paths. Bulk updates pass those paths to the corresponding update-finished hook. Feature scenarios check the reported files.

Changes: Plugin and theme update file reporting

Layer / File(s) Summary
Track changed files
src/WP_CLI/PluginUpgrader.php, src/WP_CLI/ThemeUpgrader.php, src/WP_CLI/DestructivePluginUpgrader.php, src/WP_CLI/DestructiveThemeUpgrader.php
The custom upgraders record paths from the OPcache invalidation filter, then deduplicate and sort the paths. They expose the paths through get_changed_files(). Destructive upgraders now extend the custom upgrader classes.
Wire up update-finished hooks
src/Plugin_Command.php, src/Theme_Command.php, src/WP_CLI/CommandWithUpgrade.php, phpcs.xml.dist, features/plugin-update.feature, features/theme-update.feature
Plugin and theme commands select the custom upgraders for non-forced updates. update_many fires the relevant update-finished hook with changed paths and reports an error if bulk_upgrade() returns a non-array result. Feature scenarios check the plugin and theme paths reported by the hooks.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant CommandWithUpgrade
  participant PluginUpgrader
  participant plugin_update_finished
  CommandWithUpgrade->>PluginUpgrader: Run bulk_upgrade()
  PluginUpgrader->>PluginUpgrader: Capture paths during install_package()
  CommandWithUpgrade->>PluginUpgrader: Read get_changed_files()
  CommandWithUpgrade->>plugin_update_finished: Fire hook with changed paths
Loading

Suggested reviewers: danielbachhuber, schlessera

Merge Risk: Minimal · up to f84c2

No actionable merge-blocking defect is established. The compatibility suppressions should remain; confirm normal CI checks before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Add hook to expose changed files for OPCache invalidation" matches the main change. The PR adds plugin_update_finished and theme_update_finished hooks that expose changed PHP files after wp…
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.
Full details: Title check

Explanation

The title "Add hook to expose changed files for OPCache invalidation" matches the main change. The PR adds plugin_update_finished and theme_update_finished hooks that expose changed PHP files after wp plugin update and wp theme update, so other tools can invalidate OPcache. The title is specific and names the primary change. It does not list every detail, such as the upgrader classes or the phpcs exclusion, which is acceptable.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • 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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e194b42e-6cb9-469f-b3a6-22024f8fccc7
Commits

Reviewing files that changed from the base of the PR and between ac1fd68 and f84c2cd.

Files selected for processing: 10

  • features/plugin-update.feature
  • features/theme-update.feature
  • phpcs.xml.dist
  • src/Plugin_Command.php
  • src/Theme_Command.php
  • src/WP_CLI/CommandWithUpgrade.php
  • src/WP_CLI/DestructivePluginUpgrader.php
  • src/WP_CLI/DestructiveThemeUpgrader.php
  • src/WP_CLI/PluginUpgrader.php
  • src/WP_CLI/ThemeUpgrader.php

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@swissspidy

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@swissspidy
swissspidy merged commit eff3281 into main Nov 24, 2026
57 of 58 checks passed
@swissspidy
swissspidy deleted the copilot/fix-opcache-invalidation branch November 24, 2026 21:05
@github-actions github-actions Bot added this to the 3.1.0 milestone Nov 24, 2026
@drzraf

drzraf commented Nov 25, 2026

Copy link
Copy Markdown

Sample cronjob I intend to use to take advantage of this hook:

#!/bin/bash

PLUGINS_NO_AUTO_UPDATE=foo,bar,advanced-custom-fields-pro
WP=/usr/local/bin/wp

path="$1" && shift
# Remaining arguments, if any, are forwarded to cachetool (eg. --fcgi=/run/php/<pool>.sock)
[[ ! -d $path ]] && exit 1

update=(--path="$path" plugin update --all --patch --quiet --no-color --exclude="$PLUGINS_NO_AUTO_UPDATE")

output=$($WP "${update[@]}" --dry-run)
[[ -z $output ]] && exit 0

# wp-cli/extension-command >= 3.1.0 reports the files it rewrote through the
# `plugin_update_finished` hook (https://github.com/wp-cli/extension-command/pull/501,
# https://github.com/wp-cli/extension-command/issues/444). Older versions never fire it:
# $updated then stays empty and we fall back to a full reset, as before.
updated=$(mktemp) hook=$(mktemp --suffix=.php)
trap 'rm -f "$updated" "$hook"' EXIT

cat > "$hook" <<'PHP'
<?php
// Report the directory of each updated plugin, one per line.
WP_CLI::add_hook('plugin_update_finished', function ($files) {
	$dirs = [];
	foreach ((array) $files as $file) {
		if (0 === strpos($file, WP_PLUGIN_DIR . '/')) {
			$dirs[] = WP_PLUGIN_DIR . '/' . strtok(substr($file, strlen(WP_PLUGIN_DIR) + 1), '/');
		}
	}
	if ($dirs) {
		file_put_contents(getenv('WP_UPDATED_PLUGINS_DIRS'), implode("\n", array_unique($dirs)) . "\n");
	}
});
PHP

WP_UPDATED_PLUGINS_DIRS="$updated" $WP "${update[@]}" --require="$hook"

if [[ -s $updated ]] && type -P cachetool &> /dev/null; then
	# Selective invalidation, at the PHP-FPM level. `opcache:invalidate:scripts` expects a
	# single regexp matched against the cached scripts (so: one call per updated plugin, and
	# files dropped by the update are invalidated too, unlike with `wp opcache invalidate`).
	while read -r dir; do
		sudo cachetool "$@" opcache:invalidate:scripts "^$dir/"
	done < "$updated"
elif $WP --path="$path" cli has-command opcache; then
	$WP --path="$path" opcache clear;
elif type -P cachetool &> /dev/null; then
	sudo cachetool "$@" opcache:reset
fi

find "$path/../app/plugins" -maxdepth 1 -type d -empty

if type -P yq &>/dev/null; then
	p=$(realpath "$path/../../")
	core_version=$(yq -r '.require["roots/wordpress-no-content"]|sub("[^0-9]"; "")' "$p/composer.json")
	composer --working-dir="$p" update "roots/wordpress-no-content:^${core_version}"
fi

true;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

command:plugin-update Related to 'plugin update' command scope:testing Related to testing state:unconfirmed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

opcache invalidation

4 participants