<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[11122] sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc: Translate: Add a CLI command to export .json translation files for a project (plugin/theme) into a WPLANGDIR export folder.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="http://meta.trac.wordpress.org/changeset/11122">11122</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"http://meta.trac.wordpress.org/changeset/11122","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>dd32</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2021-07-19 03:13:43 +0000 (Mon, 19 Jul 2021)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>Translate: Add a CLI command to export .json translation files for a project (plugin/theme) into a WPLANGDIR export folder.

This is to be used by the WordPress.org translation deployment process for the WordPress.org-site primarily, but might be useful in other ways.

See https://github.com/WordPress/pattern-directory/issues/282.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#sitestrunkwordpressorgpublic_htmlwpcontentpluginswporggpcustomizationsincclasspluginphp">sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/class-plugin.php</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#sitestrunkwordpressorgpublic_htmlwpcontentpluginswporggpcustomizationsinccliclassexportjsonphp">sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/cli/class-export-json.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="sitestrunkwordpressorgpublic_htmlwpcontentpluginswporggpcustomizationsincclasspluginphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/class-plugin.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/class-plugin.php     2021-07-16 20:58:19 UTC (rev 11121)
+++ sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/class-plugin.php       2021-07-19 03:13:43 UTC (rev 11122)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -428,6 +428,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">                WP_CLI::add_command( 'wporg-translate mass-create-sets', __NAMESPACE__ . '\CLI\Mass_Create_Sets' );
</span><span class="cx" style="display: block; padding: 0 10px">                WP_CLI::add_command( 'wporg-translate make-core-pot', __NAMESPACE__ . '\CLI\Make_Core_Pot' );
</span><span class="cx" style="display: block; padding: 0 10px">                WP_CLI::add_command( 'wporg-translate export', __NAMESPACE__ . '\CLI\Export' );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                WP_CLI::add_command( 'wporg-translate export-json', __NAMESPACE__ . '\CLI\Export_Json' );
+
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span></span></pre></div>
<a id="sitestrunkwordpressorgpublic_htmlwpcontentpluginswporggpcustomizationsinccliclassexportjsonphpfromrev11116sitestrunkwordpressorgpublic_htmlwpcontentpluginswporggpcustomizationsinccliclasslanguagepackphp"></a>
<div class="copfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Copied: sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/cli/class-export-json.php (from rev 11116, sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/cli/class-language-pack.php)</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/cli/class-export-json.php                            (rev 0)
+++ sites/trunk/wordpress.org/public_html/wp-content/plugins/wporg-gp-customizations/inc/cli/class-export-json.php      2021-07-19 03:13:43 UTC (rev 11122)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -0,0 +1,225 @@
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+<?php
+
+namespace WordPressdotorg\GlotPress\Customizations\CLI;
+
+use GP;
+use GP_Locales;
+use WP_CLI;
+use WP_CLI_Command;
+
+class Export_JSON extends WP_CLI_Command {
+
+       /**
+        * Export plugin/themes JSON translation files for a project into a WPLANGDIR type directory.
+        *
+        * ## OPTIONS
+        *
+        * <project>
+        * : The GlotPress project to export.
+        *
+        * <locale>
+        * : Locale to export json translations for.
+        * 
+        * <type>
+        * : The type of the project. 'plugin', 'theme', or 'both'.
+        * 
+        * <textdomain>
+        * : The textdomain of the project.
+        * 
+        * <export-directory>
+        * : The directory to export the JSON files into. Must contain `plugins` and `themes` sub-folders.
+        * 
+        * [--locale-slug]
+        * : Slug of the locale. Default: 'default'.
+        * 
+        * [--strip-path-prefix]
+        * : Path prefix to strip from the file prefix. Pass 'guess' to strip all plugin/theme looking prefixes. Default: false.
+        */
+       public function __invoke( $args, $assoc_args ) {
+               $project_slug = $args[0];
+               $locale       = $args[1];
+               $type         = $args[2] === 'both' ? false : $args[2];
+               $textdomain   = $args[3];
+               $export_dir   = $args[4];
+
+               $args = wp_parse_args( $assoc_args, [
+                       'locale-slug'       => 'default',
+                       'strip-path-prefix' => false,
+               ] );
+
+               $gp_project = GP::$project->by_path( $project_slug );
+               if ( ! $gp_project ) {
+                       WP_CLI::error( 'Invalid project slug.' );
+               }
+
+               if ( ! is_writable( $export_dir ) || ! is_dir( $export_dir ) ) {
+                       WP_CLI::error( 'Invalid export directory.' );
+               }
+
+               $translation_set = GP::$translation_set->by_project_id_slug_and_locale( $gp_project->id, $args['locale-slug'], $locale );
+               if ( ! $translation_set ) {
+                       WP_CLI::error( 'Invalid translation set.' );
+               }
+
+               // Get WP locale.
+               $gp_locale = GP_Locales::by_slug( $translation_set->locale );
+               if ( ! isset( $gp_locale->wp_locale ) ) {
+                       WP_CLI::error( 'Invalid translation set.' );
+               }
+
+               // Check if any current translations exist.
+               if ( 0 === $translation_set->current_count() ) {
+                       WP_CLI::log( 'No current translations available.' );
+                       return;
+               }
+
+               $entries = GP::$translation->for_export( $gp_project, $translation_set, [ 'status' => 'current' ] );
+               if ( ! $entries ) {
+                       WP_CLI::warning( 'No current translations available.' );
+                       return;
+               }
+
+               // Build a mapping based on where the translation entries occur.
+               $plugins = $this->build_mapping( $entries, 'plugins', $type );
+               $themes  = $this->build_mapping( $entries, 'themes', $type );
+
+               // Strip the path prefix if required.
+               if ( $args['strip-path-prefix'] ) {
+                       $plugins = $this->strip_path_prefix( $plugins, $args['strip-path-prefix'] );
+                       $themes  = $this->strip_path_prefix( $themes, $args['strip-path-prefix'] );
+               }
+
+               // Create JED json files for each JS file.
+               $plugin_json_files = $this->build_json_files( $gp_project, $gp_locale, $set, $plugins, "{$export_dir}/plugins/{$textdomain}-{$gp_locale->wp_locale}" );
+               $theme_json_files  = $this->build_json_files( $gp_project, $gp_locale, $set, $themes, "{$export_dir}/themes/{$textdomain}-{$gp_locale->wp_locale}" );
+
+               WP_CLI::success( "JSON Files for {$project_slug} {$locale} generated." );
+       }
+
+       /**
+        * Build a mapping of JS files to translation entries occurring in those files.
+        * Translation entries occurring in other files are skipped.
+        *
+        * @param Translation_Entry[] $entries      The translation entries to map.
+        * @param string              $type_limiter Limit to this kind of string. 'themes', 'plugins'.
+        * @param string              $type         The type of the project. false to guess.
+        * @return array The mapping of sources to translation entries.
+        */
+       private function build_mapping( $entries, $type_limiter, $type ) {
+               $mapping = [];
+
+               foreach ( $entries as $entry ) {
+                       /** @var Translation_Entry $entry */
+
+                       // Find all unique sources this translation originates from.
+                       if ( ! empty( $entry->references ) ) {
+                               $sources = array_map(
+                                       function ( $reference ) {
+                                               $parts = explode( ':', $reference );
+                                               $file  = $parts[0];
+
+                                               if ( substr( $file, -7 ) === '.min.js' ) {
+                                                       return substr( $file, 0, -7 ) . '.js';
+                                               }
+
+                                               if ( substr( $file, -3 ) === '.js' ) {
+                                                       return $file;
+                                               }
+
+                                               return false;
+                                       },
+                                       $entry->references
+                               );
+
+                               $sources = array_unique( $sources );
+                       }
+
+                       foreach ( array_filter( $sources ) as $source ) {
+                               if ( $type_limiter ) {
+                                       $filetype = $type;
+                                       if ( $type ) {
+                                               $filetype = $type;
+                                       } elseif ( preg_match( '!wp-content/(themes|plugins)/!', $source, $m ) ) {
+                                               $filetype = $m[1];
+                                       } elseif ( preg_match( '!^/?(themes|plugins)/!', $source, $m ) ) {
+                                               $filetype = $m[1];
+                                       }
+
+                                       if ( $filetype !== $type_limiter ) {
+                                               continue;
+                                       }
+                               }
+
+                               $mapping[ $source ][] = $entry;
+                       }
+               }
+
+               return $mapping;
+       }
+
+       /**
+        * Strip a leading path off the keys of the mapping array.
+        * 
+        * @param array  $mapping The mapping array returned by build_mapping.
+        * @param string $prefix  The prefix to strip, or 'magic' to strip all plugin/theme-looking paths.
+        * @return array The $mapping object with paths striped.
+        */
+       private function strip_path_prefix( $mapping, $prefix ) {
+               $result = [];
+
+               foreach ( $mapping as $file => $entries ) {
+                       if ( 'guess' === $prefix ) {
+                               $file = preg_replace( '!^(.*wp-content)?/?(plugins|themes)/[^/]+/!i', '', $file );
+                       } else {
+                               if ( $prefix === substr( $file, 0, strlen( $prefix ) ) ) {
+                                       $file = substr( $file, strlen( $prefix ) );
+                               }
+                       }
+
+                       $result[ $file ] = $entries;
+               }
+
+               return $result;
+       }
+
+       /**
+        * Builds a a separate JSON file with translations for each JavaScript file.
+        *
+        * @param GP_Project          $gp_project The GlotPress project.
+        * @param GP_Locale           $gp_locale  The GlotPress locale.
+        * @param GP_Translation_Set  $set        The translation set.
+        * @param array               $mapping    A mapping of files to translation entries.
+        * @param string              $base_dest  Destination file name.
+        * @return array An array of translation files built, may be empty if no translations in JS files exist.
+        */
+       private function build_json_files( $gp_project, $gp_locale, $set, $mapping, $base_dest ) {
+               $files  = array();
+               $format = gp_array_get( GP::$formats, 'jed1x' );
+
+               foreach ( $mapping as $file => $entries ) {
+                       // Don't create JSON files for source files.
+                       if ( 0 === strpos( $file, 'src/' ) || false !== strpos( $file, '/src/' ) ) {
+                               continue;
+                       }
+
+                       // Get the translations in Jed 1.x compatible JSON format.
+                       $json_content = $format->print_exported_file( $gp_project, $gp_locale, $set, $entries );
+
+                       // Decode and add comment with file reference for debugging.
+                       $json_content_decoded          = json_decode( $json_content );
+                       $json_content_decoded->comment = [ 'reference' => $file ];
+
+                       $json_content = wp_json_encode( $json_content_decoded );
+
+                       $hash = md5( $file );
+                       $dest = "{$base_dest}-{$hash}.json";
+
+                       file_put_contents( $dest, $json_content );
+
+                       $files[] = $dest;
+               }
+
+               return $files;
+       }
+
+}
</ins></span></pre>
</div>
</div>

</body>
</html>