build: reformat (clang) extract.js (#33523)

PR Close #33523
This commit is contained in:
Pete Bacon Darwin 2019-11-02 15:33:23 +00:00 committed by atscott
parent 85298e345d
commit 502dd89290
1 changed files with 80 additions and 80 deletions

View File

@ -23,7 +23,8 @@ const I18N_DATA_EXTRA_FOLDER = `${I18N_DATA_FOLDER}/extra`;
const RELATIVE_I18N_FOLDER = path.resolve(__dirname, `../../../${I18N_FOLDER}`); const RELATIVE_I18N_FOLDER = path.resolve(__dirname, `../../../${I18N_FOLDER}`);
const RELATIVE_I18N_CORE_FOLDER = path.resolve(__dirname, `../../../${I18N_CORE_FOLDER}`); const RELATIVE_I18N_CORE_FOLDER = path.resolve(__dirname, `../../../${I18N_CORE_FOLDER}`);
const RELATIVE_I18N_DATA_FOLDER = path.resolve(__dirname, `../../../${I18N_DATA_FOLDER}`); const RELATIVE_I18N_DATA_FOLDER = path.resolve(__dirname, `../../../${I18N_DATA_FOLDER}`);
const RELATIVE_I18N_DATA_EXTRA_FOLDER = path.resolve(__dirname, `../../../${I18N_DATA_EXTRA_FOLDER}`); const RELATIVE_I18N_DATA_EXTRA_FOLDER =
path.resolve(__dirname, `../../../${I18N_DATA_EXTRA_FOLDER}`);
const DEFAULT_RULE = 'function anonymous(n\n/*``*/) {\nreturn"other"\n}'; const DEFAULT_RULE = 'function anonymous(n\n/*``*/) {\nreturn"other"\n}';
const EMPTY_RULE = 'function anonymous(n\n/*``*/) {\n\n}'; const EMPTY_RULE = 'function anonymous(n\n/*``*/) {\n\n}';
const WEEK_DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; const WEEK_DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
@ -72,9 +73,12 @@ module.exports = (gulp, done) => {
console.log(`${index + 1}/${LOCALES.length}`); console.log(`${index + 1}/${LOCALES.length}`);
console.log(`\t${I18N_DATA_FOLDER}/${locale}.ts`); console.log(`\t${I18N_DATA_FOLDER}/${locale}.ts`);
fs.writeFileSync(`${RELATIVE_I18N_DATA_FOLDER}/${locale}.ts`, locale === 'en'? localeEnFile : generateLocale(locale, localeData, baseCurrencies)); fs.writeFileSync(
`${RELATIVE_I18N_DATA_FOLDER}/${locale}.ts`,
locale === 'en' ? localeEnFile : generateLocale(locale, localeData, baseCurrencies));
console.log(`\t${I18N_DATA_EXTRA_FOLDER}/${locale}.ts`); console.log(`\t${I18N_DATA_EXTRA_FOLDER}/${locale}.ts`);
fs.writeFileSync(`${RELATIVE_I18N_DATA_EXTRA_FOLDER}/${locale}.ts`, generateLocaleExtra(locale, localeData)); fs.writeFileSync(
`${RELATIVE_I18N_DATA_EXTRA_FOLDER}/${locale}.ts`, generateLocaleExtra(locale, localeData));
}); });
console.log(`${LOCALES.length} locale files generated.`); console.log(`${LOCALES.length} locale files generated.`);
@ -82,13 +86,14 @@ module.exports = (gulp, done) => {
const format = require('gulp-clang-format'); const format = require('gulp-clang-format');
const clangFormat = require('clang-format'); const clangFormat = require('clang-format');
return gulp return gulp
.src([ .src(
`${I18N_DATA_FOLDER}/**/*.ts`, [
`${I18N_FOLDER}/currencies.ts`, `${I18N_DATA_FOLDER}/**/*.ts`, `${I18N_FOLDER}/currencies.ts`,
`${I18N_CORE_FOLDER}/locale_en.ts` `${I18N_CORE_FOLDER}/locale_en.ts`
], {base: '.'}) ],
.pipe(format.format('file', clangFormat)) {base: '.'})
.pipe(gulp.dest('.')); .pipe(format.format('file', clangFormat))
.pipe(gulp.dest('.'));
}; };
/** /**
@ -96,16 +101,16 @@ module.exports = (gulp, done) => {
*/ */
function generateLocale(locale, localeData, baseCurrencies) { function generateLocale(locale, localeData, baseCurrencies) {
// [ localeId, dateTime, number, currency, pluralCase ] // [ localeId, dateTime, number, currency, pluralCase ]
let data = stringify([ let data =
locale, stringify(
...getDateTimeTranslations(localeData), [
...getDateTimeSettings(localeData), locale, ...getDateTimeTranslations(localeData), ...getDateTimeSettings(localeData),
...getNumberSettings(localeData), ...getNumberSettings(localeData), ...getCurrencySettings(locale, localeData),
...getCurrencySettings(locale, localeData), generateLocaleCurrencies(localeData, baseCurrencies)
generateLocaleCurrencies(localeData, baseCurrencies) ],
], true) true)
// We remove "undefined" added by spreading arrays when there is no value // We remove "undefined" added by spreading arrays when there is no value
.replace(/undefined/g, 'u'); .replace(/undefined/g, 'u');
// adding plural function after, because we don't want it as a string // adding plural function after, because we don't want it as a string
data = data.substring(0, data.lastIndexOf(']')) + `, plural]`; data = data.substring(0, data.lastIndexOf(']')) + `, plural]`;
@ -120,7 +125,8 @@ export default ${data};
} }
/** /**
* Generate a file that contains extra data (for now: day period rules, and extended day period data) * Generate a file that contains extra data
* (for now: day period rules, and extended day period data)
*/ */
function generateLocaleExtra(locale, localeData) { function generateLocaleExtra(locale, localeData) {
const dayPeriods = getDayPeriodsNoAmPm(localeData); const dayPeriods = getDayPeriodsNoAmPm(localeData);
@ -136,8 +142,7 @@ function generateLocaleExtra(locale, localeData) {
} }
const dayPeriodsFormat = removeDuplicates([ const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow), objectValues(dayPeriods.format.narrow), objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide) objectValues(dayPeriods.format.wide)
]); ]);
@ -243,13 +248,16 @@ export const CURRENCIES_EN: {[code: string]: CurrenciesSymbols | [string | undef
/** /**
* Returns data for the chosen day periods * Returns data for the chosen day periods
* @returns {format: {narrow / abbreviated / wide: [...]}, stand-alone: {narrow / abbreviated / wide: [...]}} * @returns {
* format: {narrow / abbreviated / wide: [...]},
* stand-alone: {narrow / abbreviated / wide: [...]}
* }
*/ */
function getDayPeriods(localeData, dayPeriodsList) { function getDayPeriods(localeData, dayPeriodsList) {
const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`); const dayPeriods = localeData.main(`dates/calendars/gregorian/dayPeriods`);
const result = {}; const result = {};
// cleaning up unused keys // cleaning up unused keys
Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone Object.keys(dayPeriods).forEach(key1 => { // format / stand-alone
result[key1] = {}; result[key1] = {};
Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide Object.keys(dayPeriods[key1]).forEach(key2 => { // narrow / abbreviated / wide
result[key1][key2] = {}; result[key1][key2] = {};
@ -275,13 +283,16 @@ function getDayPeriodsAmPm(localeData) {
* Returns the extra day periods (without am/pm) * Returns the extra day periods (without am/pm)
*/ */
function getDayPeriodsNoAmPm(localeData) { function getDayPeriodsNoAmPm(localeData) {
return getDayPeriods(localeData, ['noon', 'midnight', 'morning1', 'morning2', 'afternoon1', return getDayPeriods(localeData, [
'afternoon2', 'evening1', 'evening2', 'night1', 'night2']); 'noon', 'midnight', 'morning1', 'morning2', 'afternoon1', 'afternoon2', 'evening1', 'evening2',
'night1', 'night2'
]);
} }
/** /**
* Returns date-related translations for a locale * Returns date-related translations for a locale
* @returns [ dayPeriodsFormat, dayPeriodsStandalone, daysFormat, dayStandalone, monthsFormat, monthsStandalone, eras ] * @returns [ dayPeriodsFormat, dayPeriodsStandalone, daysFormat, dayStandalone, monthsFormat,
* monthsStandalone, eras ]
* each value: [ narrow, abbreviated, wide, short? ] * each value: [ narrow, abbreviated, wide, short? ]
*/ */
function getDateTimeTranslations(localeData) { function getDateTimeTranslations(localeData) {
@ -291,8 +302,7 @@ function getDateTimeTranslations(localeData) {
const dayPeriods = getDayPeriodsAmPm(localeData); const dayPeriods = getDayPeriodsAmPm(localeData);
const dayPeriodsFormat = removeDuplicates([ const dayPeriodsFormat = removeDuplicates([
objectValues(dayPeriods.format.narrow), objectValues(dayPeriods.format.narrow), objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.abbreviated),
objectValues(dayPeriods.format.wide) objectValues(dayPeriods.format.wide)
]); ]);
@ -303,22 +313,17 @@ function getDateTimeTranslations(localeData) {
]); ]);
const daysFormat = removeDuplicates([ const daysFormat = removeDuplicates([
objectValues(dayNames.format.narrow), objectValues(dayNames.format.narrow), objectValues(dayNames.format.abbreviated),
objectValues(dayNames.format.abbreviated), objectValues(dayNames.format.wide), objectValues(dayNames.format.short)
objectValues(dayNames.format.wide),
objectValues(dayNames.format.short)
]); ]);
const daysStandalone = removeDuplicates([ const daysStandalone = removeDuplicates([
objectValues(dayNames['stand-alone'].narrow), objectValues(dayNames['stand-alone'].narrow), objectValues(dayNames['stand-alone'].abbreviated),
objectValues(dayNames['stand-alone'].abbreviated), objectValues(dayNames['stand-alone'].wide), objectValues(dayNames['stand-alone'].short)
objectValues(dayNames['stand-alone'].wide),
objectValues(dayNames['stand-alone'].short)
]); ]);
const monthsFormat = removeDuplicates([ const monthsFormat = removeDuplicates([
objectValues(monthNames.format.narrow), objectValues(monthNames.format.narrow), objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.abbreviated),
objectValues(monthNames.format.wide) objectValues(monthNames.format.wide)
]); ]);
@ -337,8 +342,7 @@ function getDateTimeTranslations(localeData) {
const dateTimeTranslations = [ const dateTimeTranslations = [
...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]), ...removeDuplicates([dayPeriodsFormat, dayPeriodsStandalone]),
...removeDuplicates([daysFormat, daysStandalone]), ...removeDuplicates([daysFormat, daysStandalone]),
...removeDuplicates([monthsFormat, monthsStandalone]), ...removeDuplicates([monthsFormat, monthsStandalone]), eras
eras
]; ];
return dateTimeTranslations; return dateTimeTranslations;
@ -352,10 +356,8 @@ function getDateTimeTranslations(localeData) {
function getDateTimeFormats(localeData) { function getDateTimeFormats(localeData) {
function getFormats(data) { function getFormats(data) {
return removeDuplicates([ return removeDuplicates([
data.short._value || data.short, data.short._value || data.short, data.medium._value || data.medium,
data.medium._value || data.medium, data.long._value || data.long, data.full._value || data.full
data.long._value || data.long,
data.full._value || data.full
]); ]);
} }
@ -363,11 +365,7 @@ function getDateTimeFormats(localeData) {
const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats'); const timeFormats = localeData.main('dates/calendars/gregorian/timeFormats');
const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats'); const dateTimeFormats = localeData.main('dates/calendars/gregorian/dateTimeFormats');
return [ return [getFormats(dateFormats), getFormats(timeFormats), getFormats(dateTimeFormats)];
getFormats(dateFormats),
getFormats(timeFormats),
getFormats(dateTimeFormats)
];
} }
/** /**
@ -375,7 +373,8 @@ function getDateTimeFormats(localeData) {
* @returns string[] * @returns string[]
*/ */
function getDayPeriodRules(localeData) { function getDayPeriodRules(localeData) {
const dayPeriodRules = localeData.get(`supplemental/dayPeriodRuleSet/${localeData.attributes.language}`); const dayPeriodRules =
localeData.get(`supplemental/dayPeriodRuleSet/${localeData.attributes.language}`);
const rules = {}; const rules = {};
if (dayPeriodRules) { if (dayPeriodRules) {
Object.keys(dayPeriodRules).forEach(key => { Object.keys(dayPeriodRules).forEach(key => {
@ -404,11 +403,11 @@ function getFirstDayOfWeek(localeData) {
*/ */
function getWeekendRange(localeData) { function getWeekendRange(localeData) {
const startDay = const startDay =
localeData.get(`supplemental/weekData/weekendStart/${localeData.attributes.territory}`) || localeData.get(`supplemental/weekData/weekendStart/${localeData.attributes.territory}`) ||
localeData.get('supplemental/weekData/weekendStart/001'); localeData.get('supplemental/weekData/weekendStart/001');
const endDay = const endDay =
localeData.get(`supplemental/weekData/weekendEnd/${localeData.attributes.territory}`) || localeData.get(`supplemental/weekData/weekendEnd/${localeData.attributes.territory}`) ||
localeData.get('supplemental/weekData/weekendEnd/001'); localeData.get('supplemental/weekData/weekendEnd/001');
return [WEEK_DAYS.indexOf(startDay), WEEK_DAYS.indexOf(endDay)]; return [WEEK_DAYS.indexOf(startDay), WEEK_DAYS.indexOf(endDay)];
} }
@ -417,13 +416,17 @@ function getWeekendRange(localeData) {
* @returns [ firstDayOfWeek, weekendRange, formats ] * @returns [ firstDayOfWeek, weekendRange, formats ]
*/ */
function getDateTimeSettings(localeData) { function getDateTimeSettings(localeData) {
return [getFirstDayOfWeek(localeData), getWeekendRange(localeData), ...getDateTimeFormats(localeData)]; return [
getFirstDayOfWeek(localeData), getWeekendRange(localeData), ...getDateTimeFormats(localeData)
];
} }
/** /**
* Returns the number symbols and formats for a locale * Returns the number symbols and formats for a locale
* @returns [ symbols, formats ] * @returns [ symbols, formats ]
* symbols: [ decimal, group, list, percentSign, plusSign, minusSign, exponential, superscriptingExponent, perMille, infinity, nan, timeSeparator, currencyDecimal?, currencyGroup? ] * symbols: [ decimal, group, list, percentSign, plusSign, minusSign, exponential,
* superscriptingExponent, perMille, infinity, nan, timeSeparator, currencyDecimal?, currencyGroup?
* ]
* formats: [ currency, decimal, percent, scientific ] * formats: [ currency, decimal, percent, scientific ]
*/ */
function getNumberSettings(localeData) { function getNumberSettings(localeData) {
@ -455,10 +458,7 @@ function getNumberSettings(localeData) {
symbolValues.push(symbols.currencyGroup); symbolValues.push(symbols.currencyGroup);
} }
return [ return [symbolValues, [decimalFormat, percentFormat, currencyFormat, scientificFormat]];
symbolValues,
[decimalFormat, percentFormat, currencyFormat, scientificFormat]
];
} }
/** /**
@ -471,8 +471,9 @@ function getCurrencySettings(locale, localeData) {
// find the currency currently used in this country // find the currency currently used in this country
const currencies = const currencies =
localeData.get(`supplemental/currencyData/region/${localeData.attributes.territory}`) || localeData.get(`supplemental/currencyData/region/${localeData.attributes.territory}`) ||
localeData.get(`supplemental/currencyData/region/${localeData.attributes.language.toUpperCase()}`); localeData.get(
`supplemental/currencyData/region/${localeData.attributes.language.toUpperCase()}`);
if (currencies) { if (currencies) {
currencies.some(currency => { currencies.some(currency => {
@ -492,7 +493,8 @@ function getCurrencySettings(locale, localeData) {
let currencySettings = [undefined, undefined]; let currencySettings = [undefined, undefined];
if (currentCurrency) { if (currentCurrency) {
currencySettings = [currencyInfo[currentCurrency].symbol, currencyInfo[currentCurrency].displayName]; currencySettings =
[currencyInfo[currentCurrency].symbol, currencyInfo[currentCurrency].displayName];
} }
return currencySettings; return currencySettings;
@ -517,23 +519,21 @@ function getPluralFunction(locale) {
fn = DEFAULT_RULE; fn = DEFAULT_RULE;
} }
fn = fn fn = fn.replace(
.replace( toRegExp('function anonymous(n\n/*``*/) {\n'),
toRegExp('function anonymous(n\n/*``*/) {\n'), 'function plural(n: number): number {\n ')
'function plural(n: number): number {\n ') .replace(toRegExp('var'), 'let')
.replace(toRegExp('var'), 'let') .replace(toRegExp('if(typeof n==="string")n=parseInt(n,10);'), '')
.replace(toRegExp('if(typeof n==="string")n=parseInt(n,10);'), '') .replace(toRegExp('\n}'), ';\n}');
.replace(toRegExp('\n}'), ';\n}');
// The replacement values must match the `Plural` enum from common. // The replacement values must match the `Plural` enum from common.
// We do not use the enum directly to avoid depending on that package. // We do not use the enum directly to avoid depending on that package.
return fn return fn.replace(toRegExp('"zero"'), ' 0')
.replace(toRegExp('"zero"'), ' 0') .replace(toRegExp('"one"'), ' 1')
.replace(toRegExp('"one"'), ' 1') .replace(toRegExp('"two"'), ' 2')
.replace(toRegExp('"two"'), ' 2') .replace(toRegExp('"few"'), ' 3')
.replace(toRegExp('"few"'), ' 3') .replace(toRegExp('"many"'), ' 4')
.replace(toRegExp('"many"'), ' 4') .replace(toRegExp('"other"'), ' 5');
.replace(toRegExp('"other"'), ' 5');
} }
/** /**
@ -562,7 +562,7 @@ function objectValues(obj) {
*/ */
function removeDuplicates(data) { function removeDuplicates(data) {
const dedup = [data[0]]; const dedup = [data[0]];
for(let i = 1; i < data.length; i++) { for (let i = 1; i < data.length; i++) {
if (stringify(data[i]) !== stringify(data[i - 1])) { if (stringify(data[i]) !== stringify(data[i - 1])) {
dedup.push(data[i]); dedup.push(data[i]);
} else { } else {