From be093afd8f8ed45794b51f364efacd5da948c778 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Thu, 19 Dec 2024 18:11:28 +0100 Subject: [PATCH] Add `restrictDirectories` option for style variations --- src/IterableCodeExtractor.php | 19 +++++++++++++++---- src/MakePotCommand.php | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/IterableCodeExtractor.php b/src/IterableCodeExtractor.php index 8611ca2..51b3e53 100644 --- a/src/IterableCodeExtractor.php +++ b/src/IterableCodeExtractor.php @@ -23,9 +23,10 @@ trait IterableCodeExtractor { * @param array $options { * Optional. An array of options passed down to static::fromString() * - * @type bool $wpExtractTemplates Extract 'Template Name' headers in theme files. Default 'false'. - * @type bool $wpExtractPatterns Extract 'Title' and 'Description' headers in pattern files. Default 'false'. - * @type array $restrictFileNames Skip all files which are not included in this array. + * @type bool $wpExtractTemplates Extract 'Template Name' headers in theme files. Default 'false'. + * @type bool $wpExtractPatterns Extract 'Title' and 'Description' headers in pattern files. Default 'false'. + * @type array $restrictFileNames Skip all files which are not included in this array. + * @type array $restrictDirectories Skip all directories which are not included in this array. * } * @return null */ @@ -38,8 +39,18 @@ public static function fromFile( $file_or_files, Translations $translations, arr } } + $relative_file_path = ltrim( str_replace( static::$dir, '', Utils\normalize_path( $file ) ), '/' ); + // Make sure a relative file path is added as a comment. - $options['file'] = ltrim( str_replace( static::$dir, '', Utils\normalize_path( $file ) ), '/' ); + $options['file'] = $relative_file_path; + + if ( ! empty( $options['restrictDirectories'] ) ) { + $top_level_dirname = explode( '/', $relative_file_path )[0]; + + if ( ! in_array( $top_level_dirname, $options['restrictDirectories'], true ) ) { + continue; + } + } $text = file_get_contents( $file ); diff --git a/src/MakePotCommand.php b/src/MakePotCommand.php index 6575010..8688096 100644 --- a/src/MakePotCommand.php +++ b/src/MakePotCommand.php @@ -718,6 +718,24 @@ protected function extract_strings() { 'addReferences' => $this->location, ] ); + + // Themes can have style variations in the top-level "styles" folder. + // They're like theme.json but can have any name. + if ( $is_theme ) { + JsonSchemaExtractor::fromDirectory( + $this->source, + $translations, + [ + 'restrictDirectories' => [ 'styles' ], + 'schema' => JsonSchemaExtractor::THEME_JSON_SOURCE, + 'schemaFallback' => JsonSchemaExtractor::THEME_JSON_FALLBACK, + 'include' => $this->include, + 'exclude' => $this->exclude, + 'extensions' => [ 'json' ], + 'addReferences' => $this->location, + ] + ); + } } } catch ( \Exception $e ) { WP_CLI::error( $e->getMessage() );