diff --git a/README.md b/README.md index 77e4e3d..33a11bb 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,14 @@ task('deploy', [ ]); ``` +### Purging page caches on deploy + +`purge.php` purges the page and edge caches as the `purge` setting says: +`soft` (the default), `hard`, `auto` (only when the built assets changed) or +`none`. A site sets its own default in `deploy.php`, and a deploy overrides it +with `-o purge=hard`. The modes and the setup are documented in +[`purge.php`](purge.php). + ### Provided commands ```sh diff --git a/purge.php b/purge.php new file mode 100644 index 0000000..203d0eb --- /dev/null +++ b/purge.php @@ -0,0 +1,117 @@ + escapeshellarg(parse($dir)), get('assets_dirs'))); + + return run("{ cd $root && find $dirs -type f -exec md5sum {} +; } 2>/dev/null | LC_ALL=C sort | md5sum"); +} + +desc('Check whether the built assets changed'); +task('cache:check_assets', function () { + // Fail an invalid mode before the release goes live, not after. + purgeMode(); + + foreach (get('assets_dirs') as $dir) { + if (! test('[ -d {{release_path}}/'.$dir.' ]')) { + warning(parse("assets_dirs: $dir isn't in the release, so every deploy purges")); + set('assets_changed', true); + + return; + } + } + + set('assets_changed', assetsChecksum('{{current_path}}') !== assetsChecksum('{{release_path}}')); +}); + +desc('Flush the object cache, without purging the page cache'); +task('cache:clear:wp:objectcache:only', function () { + // Not `wp cache flush`: kinsta-mu-plugins hooks that command and purges the + // whole Kinsta page cache after it. + run('cd {{deploy_path}}/current/web && {{bin/wp}} eval "wp_cache_flush();"'); +}); + +desc('Flush sage-cachetags (Cloudflare, Fastly, …)'); +task('cache:clear:cachetags', function () { + $hard = get('purge_hard') ? ' --hard' : ''; + run("cd {{deploy_path}}/current/web && {{bin/wp}} cachetags flush$hard"); +}); + +desc('Purge the page and edge caches as `purge` says'); +task('cache:purge', function () { + $mode = purgeMode(); + + if ($mode === 'auto') { + $mode = get('assets_changed') ? 'hard' : 'none'; + } + + info("purge: $mode"); + + if ($mode === 'none') { + return; + } + + set('purge_hard', $mode === 'hard'); + + // Best-effort: a CDN hiccup must not fail a deploy whose release is live. + foreach (get('purge_tasks') as $task) { + try { + invoke($task); + } catch (\Throwable $e) { + warning("$task failed, pages stay cached until they expire: ".$e->getMessage()); + } + } +}); + +before('deploy:symlink', 'cache:check_assets');