File size: 10,563 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
/**
* Extract i18n-calypso `translate` and @wordpress/i18n `__`, `_n`, `_x`, `_nx`
* calls into a POT file.
*
* Credits:
*
* babel-gettext-extractor
* https://github.com/getsentry/babel-gettext-extractor
*
* The MIT License (MIT)
*
* Copyright (c) 2015 jruchaud
* Copyright (c) 2015 Sentry
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
const { existsSync, mkdirSync, writeFileSync } = require( 'fs' );
const { relative, sep } = require( 'path' );
const { po } = require( 'gettext-parser' );
const { merge, isEmpty, forEach } = require( 'lodash' );
/**
* Default output headers if none specified in plugin options.
* @type {Object}
*/
const DEFAULT_HEADERS = {
'content-type': 'text/plain; charset=UTF-8',
'x-generator': 'babel-plugin-i18n-calypso',
};
/**
* Default directory to output the POT files.
* @type {string}
*/
const DEFAULT_DIR = 'build/';
/**
* The order of arguments in translate functions.
* @type {Object}
*/
const DEFAULT_FUNCTIONS_ARGUMENTS_ORDER = {
__: [],
_n: [ 'msgid_plural' ],
_x: [ 'msgctxt' ],
_nx: [ 'msgid_plural', null, 'msgctxt' ],
translate: [ 'msgid_plural', 'options_object' ],
};
/**
* Regular expression matching translator comment value.
* @type {RegExp}
*/
const REGEXP_TRANSLATOR_COMMENT = /^\s*translators:\s*([\s\S]+)/im;
/**
* Returns the extracted comment for a given AST traversal path if one exists.
* @param {Object} path Traversal path.
* @param {number} _originalNodeLine Private: In recursion, line number of
* the original node passed.
* @returns {string|undefined} Extracted comment.
*/
function getExtractedComment( path, _originalNodeLine ) {
const { node, parent, parentPath } = path;
// Assign original node line so we can keep track in recursion whether a
// matched comment or parent occurs on the same or previous line
if ( ! _originalNodeLine ) {
_originalNodeLine = node.loc.start.line;
}
let comment;
forEach( node.leadingComments, ( commentNode ) => {
if ( ! commentNode.loc ) {
return;
}
const { line } = commentNode.loc.end;
if ( line < _originalNodeLine - 1 || line > _originalNodeLine ) {
return;
}
const match = commentNode.value.match( REGEXP_TRANSLATOR_COMMENT );
if ( match ) {
// Extract text from matched translator prefix
comment = match[ 1 ]
.split( '\n' )
.map( ( text ) => text.trim() )
.join( ' ' );
// False return indicates to Lodash to break iteration
return false;
}
} );
if ( comment ) {
return comment;
}
if ( ! parent || ! parent.loc || ! parentPath ) {
return;
}
// Only recurse as long as parent node is on the same or previous line
const { line } = parent.loc.start;
if ( line >= _originalNodeLine - 1 && line <= _originalNodeLine ) {
return getExtractedComment( parentPath, _originalNodeLine );
}
}
/**
* Given an argument node (or recursed node), attempts to return a string
* represenation of that node's value.
* @param {Object} node AST node.
* @returns {string} String value.
*/
function getNodeAsString( node ) {
if ( undefined === node ) {
return '';
}
switch ( node.type ) {
case 'BinaryExpression':
return getNodeAsString( node.left ) + getNodeAsString( node.right );
case 'StringLiteral':
return node.value;
case 'TemplateLiteral':
return ( node.quasis || [] ).reduce( ( string, element ) => {
return ( string += element.value.cooked );
}, '' );
default:
return '';
}
}
/**
* Returns true if the specified funciton name is valid translate function name
* @param {string} name Function name to test.
* @returns {boolean} Whether function name is valid translate function name.
*/
function isValidFunctionName( name ) {
return Object.keys( DEFAULT_FUNCTIONS_ARGUMENTS_ORDER ).includes( name );
}
/**
* Returns true if the specified key of a function is valid for assignment in
* the translation object.
* @param {string} key Key to test.
* @returns {boolean} Whether key is valid for assignment.
*/
function isValidTranslationKey( key ) {
return Object.values( DEFAULT_FUNCTIONS_ARGUMENTS_ORDER ).some( ( args ) =>
args.includes( key )
);
}
/**
* Merge the properties of extracted string objects.
* @param {Object} source left-hand string object
* @param {Object} target right-hand string object
* @returns {void}
*/
function mergeStrings( source, target ) {
if ( ! source.comments.reference.includes( target.comments.reference ) ) {
source.comments.reference += '\n' + target.comments.reference;
}
if ( ! source.comments.extracted ) {
source.comments.extracted = target.comments.extracted;
} else if (
target.comments.extracted &&
! source.comments.extracted.includes( target.comments.extracted )
) {
source.comments.extracted += '\n' + target.comments.extracted;
}
// A previous singular string matches a plural string. In PO files those are merged.
if ( ! source.hasOwnProperty( 'msgid_plural' ) && target.hasOwnProperty( 'msgid_plural' ) ) {
source.msgid_plural = target.msgid_plural;
source.msgstr = target.msgstr;
}
}
module.exports = function () {
let strings = {};
let nplurals = 2;
let baseData;
let functions = { ...DEFAULT_FUNCTIONS_ARGUMENTS_ORDER };
return {
visitor: {
ImportDeclaration( path ) {
// If `translate` from `i18n-calypso` is imported with an
// alias, set the specified alias as a reference to translate.
if ( 'i18n-calypso' !== path.node.source.value ) {
return;
}
path.node.specifiers.forEach( ( specifier ) => {
if ( specifier.imported && 'translate' === specifier.imported.name && specifier.local ) {
functions[ specifier.local.name ] = functions.translate;
}
} );
},
CallExpression( path, state ) {
const { callee } = path.node;
// Determine function name by direct invocation or property name
let name;
if ( 'MemberExpression' === callee.type ) {
name = callee.property.loc ? callee.property.loc.identifierName : callee.property.name;
} else {
name = callee.loc ? callee.loc.identifierName : callee.name;
}
if ( ! isValidFunctionName( name ) ) {
return;
}
let i = 0;
const translation = {
msgid: getNodeAsString( path.node.arguments[ i++ ] ),
msgstr: '',
comments: {},
};
if ( ! translation.msgid.length ) {
return;
}
// At this point we assume we'll save data, so initialize if
// we haven't already
if ( ! baseData ) {
baseData = {
charset: 'utf-8',
headers: state.opts.headers || DEFAULT_HEADERS,
translations: {
'': {
'': {
msgid: '',
msgstr: [],
},
},
},
};
for ( const key in baseData.headers ) {
baseData.translations[ '' ][ '' ].msgstr.push(
`${ key }: ${ baseData.headers[ key ] };\n`
);
}
// Attempt to exract nplurals from header
const pluralsMatch = ( baseData.headers[ 'plural-forms' ] || '' ).match(
/nplurals\s*=\s*(\d+);/
);
if ( pluralsMatch ) {
nplurals = pluralsMatch[ 1 ];
}
}
// If exists, also assign translator comment
const translator = getExtractedComment( path );
if ( translator ) {
translation.comments.extracted = translator;
}
const { filename } = this.file.opts;
const base = state.opts.base || '.';
const pathname = relative( base, filename ).split( sep ).join( '/' );
translation.comments.reference = pathname + ':' + path.node.loc.start.line;
const functionKeys = state.opts.functions || functions[ name ];
if ( functionKeys ) {
path.node.arguments.slice( i ).forEach( ( arg, index ) => {
const key = functionKeys[ index ];
if ( 'ObjectExpression' === arg.type ) {
arg.properties.forEach( ( property ) => {
if ( 'ObjectProperty' !== property.type ) {
return;
}
if ( 'context' === property.key.name ) {
translation.msgctxt = property.value.value;
}
if ( 'comment' === property.key.name ) {
translation.comments.extracted = property.value.value;
}
} );
} else if ( isValidTranslationKey( key ) ) {
translation[ key ] = getNodeAsString( arg );
}
} );
}
// For plurals, create an empty mgstr array
if ( ( translation.msgid_plural || '' ).length ) {
translation.msgstr = Array.from( Array( nplurals ) ).map( () => '' );
}
// Create context grouping for translation if not yet exists
const { msgctxt = '', msgid } = translation;
if ( ! strings.hasOwnProperty( msgctxt ) ) {
strings[ msgctxt ] = {};
}
if ( ! strings[ msgctxt ].hasOwnProperty( msgid ) ) {
strings[ msgctxt ][ msgid ] = translation;
} else {
mergeStrings( strings[ msgctxt ][ msgid ], translation );
}
},
Program: {
enter() {
strings = {};
functions = { ...DEFAULT_FUNCTIONS_ARGUMENTS_ORDER };
},
exit( path, state ) {
if ( isEmpty( strings ) ) {
return;
}
const data = merge( {}, baseData, { translations: strings } );
const compiled = po.compile( data );
const dir = state.opts.dir || DEFAULT_DIR;
! existsSync( dir ) && mkdirSync( dir, { recursive: true } );
const { filename } = this.file.opts;
const base = state.opts.base || '.';
const pathname = relative( base, filename ).split( sep ).join( '-' );
writeFileSync( dir + pathname + '.pot', compiled );
},
},
},
};
};
|