28 private const CHANGED_CODES = [
'cdo',
'nan',
'sh',
'wuu',
'yue' ];
30 public function __construct() {
31 parent::__construct();
32 $this->addDescription(
'Backport translations from one branch to another.' );
36 'Comma separated list of message group IDs (supports * wildcard) to backport',
42 'Source path for reading updated translations. Defaults to $wgTranslateGroupRoot.',
48 'Target path for writing backported translations',
54 'Only export a group if its export path matches this prefix (relative to target-path)',
59 'never-export-languages',
60 'Languages to not export',
64 $this->requireExtension(
'Translate' );
69 $config = $this->getConfig();
71 $groupPattern = $this->getOption(
'group' ) ??
'';
73 'Starting backports for groups {groups}',
74 [
'groups' => $groupPattern ]
77 $sourcePath = $this->getOption(
'source-path' ) ?: $config->get(
'TranslateGroupRoot' );
78 if ( !is_readable( $sourcePath ) ) {
79 $this->fatalError(
"Source directory is not readable ($sourcePath)." );
82 $targetPath = $this->getOption(
'target-path' );
83 if ( !is_writable( $targetPath ) ) {
84 $this->fatalError(
"Target directory is not writable ($targetPath)." );
87 $groupIds = MessageGroups::expandWildcards( explode(
',', trim( $groupPattern ) ) );
88 $groups = MessageGroups::getGroupsById( $groupIds );
89 if ( $groups === [] ) {
90 $this->fatalError(
"Pattern $groupPattern did not match any message groups." );
93 $neverExportLanguages = $this->csv2array(
94 $this->getOption(
'never-export-languages' ) ??
''
96 $supportedLanguages = Utilities::getLanguageNames(
'en' );
98 foreach ( $groups as $group ) {
99 $groupId = $group->getId();
101 if ( !$this->hasOption(
'filter-path' ) ) {
102 $this->error(
"Skipping $groupId: Not instance of FileBasedMessageGroup" );
107 if ( !$group->getFFS() instanceof
JsonFormat ) {
108 $this->error(
"Skipping $groupId: Only JSON format is supported" );
112 if ( $this->hasOption(
'filter-path' ) ) {
113 $filter = $this->getOption(
'filter-path' );
114 $exportPath = $group->getTargetFilename(
'*' );
115 if ( !$this->matchPath( $filter, $exportPath ) ) {
120 $sourceLanguage = $group->getSourceLanguage();
122 $sourceDefinitions = $this->loadDefinitions( $group, $sourcePath, $sourceLanguage );
123 $targetDefinitions = $this->loadDefinitions( $group, $targetPath, $sourceLanguage );
124 }
catch ( RuntimeException $e ) {
126 "Skipping $groupId: Error while loading definitions: {$e->getMessage()}\n"
131 $keyCompatibilityMap = $this->getKeyCompatibilityMap(
132 $sourceDefinitions[
'MESSAGES'],
133 $targetDefinitions[
'MESSAGES'],
137 if ( array_filter( $keyCompatibilityMap ) === [] ) {
138 $this->output(
"Skipping $groupId: No compatible keys found\n" );
143 $languages = array_keys( $group->getTranslatableLanguages() ?? $supportedLanguages );
144 $languagesToSkip = $neverExportLanguages;
145 $languagesToSkip[] = $sourceLanguage;
146 $languages = array_diff( $languages, $languagesToSkip );
148 foreach ( $languages as $language ) {
149 $status = $this->backport(
153 $keyCompatibilityMap,
157 $summary[$status][] = $language;
160 $numUpdated = count( $summary[
'updated' ] ?? [] );
161 $numAdded = count( $summary[
'new' ] ?? [] );
162 if ( ( $numUpdated + $numAdded ) > 0 ) {
165 "%s: Compatible keys: %d. Updated %d languages, %d new (%s)\n",
167 count( $keyCompatibilityMap ),
170 implode(
', ', $summary[
'new' ] ?? [] )
177 private function csv2array(
string $input ): array {
179 array_map(
'trim', explode(
',', $input ) ),
180 static function ( $v ) {
186 private function matchPath(
string $prefix,
string $full ): bool {
187 $prefix =
"./$prefix";
188 $length = strlen( $prefix );
189 return substr( $full, 0, $length ) === $prefix;
192 private function loadDefinitions(
197 $file = $path .
'/' . $group->getTargetFilename( $language );
199 if ( !file_exists( $file ) ) {
200 throw new RuntimeException(
"File $file does not exist" );
203 $contents = file_get_contents( $file );
204 return $group->getFFS()->readFromVariable( $contents );
216 private function getKeyCompatibilityMap( array $source, array $target, SimpleFormat $fileFormat ): array {
218 foreach ( $target as $key => $value ) {
219 $keys[$key] = isset( $source[ $key ] ) && $fileFormat->isContentEqual( $source[ $key ], $value );
224 private function backport(
228 array $keyCompatibilityMap,
232 $sourceTemplate = $this->loadDefinitions( $group, $source, $language );
233 }
catch ( RuntimeException $e ) {
234 return 'no definitions';
238 $targetTemplate = $this->loadDefinitions( $group, $targetPath, $language );
239 }
catch ( RuntimeException $e ) {
249 $fileFormat = $group->getFFS();
253 if ( !$fileFormat instanceof JsonFormat ) {
254 throw new RuntimeException(
255 "Expected file format type: " . JsonFormat::class .
'; got: ' . get_class( $fileFormat )
259 $combinedMessages = [];
261 foreach ( $keyCompatibilityMap as $key => $isDefinitionCompatible ) {
262 $sourceValue = $sourceTemplate[
'MESSAGES'][$key] ??
null;
263 $targetValue = $targetTemplate[
'MESSAGES'][$key] ??
null;
266 if ( $targetValue !==
null ) {
267 $combinedMessages[$key] = $targetValue;
272 if ( !$isDefinitionCompatible ) {
276 if ( $sourceValue ===
null ) {
277 if ( in_array( $language, self::CHANGED_CODES,
true ) ) {
282 unset( $combinedMessages[$key] );
283 } elseif ( !$fileFormat->isContentEqual( $sourceValue, $targetValue ) ) {
285 if ( str_contains( $sourceValue,
'#FORMAL:' ) ) {
291 $combinedMessages[$key] = $sourceValue;
295 if ( !$hasUpdates ) {
300 $combinedAuthors = array_merge(
301 $targetTemplate[
'AUTHORS' ] ?? [],
302 $sourceTemplate[
'AUTHORS' ] ?? []
304 $combinedAuthors = array_unique( $combinedAuthors );
305 $combinedAuthors = $fileFormat->filterAuthors( $combinedAuthors, $language );
307 $targetTemplate[
'AUTHORS'] = $combinedAuthors;
308 $targetTemplate[
'MESSAGES'] = $combinedMessages;
310 $backportedContent = $fileFormat->generateFile( $targetTemplate );
312 $targetFilename = $targetPath .
'/' . $group->getTargetFilename( $language );
313 if ( file_exists( $targetFilename ) ) {
314 $currentContent = file_get_contents( $targetFilename );
316 if ( $fileFormat->shouldOverwrite( $currentContent, $backportedContent ) ) {
317 file_put_contents( $targetFilename, $backportedContent );
321 file_put_contents( $targetFilename, $backportedContent );
return[ 'Translate:AggregateGroupManager'=> static function(MediaWikiServices $services):AggregateGroupManager { return new AggregateGroupManager($services->getTitleFactory(), $services->get( 'Translate:MessageGroupMetadata'));}, 'Translate:AggregateGroupMessageGroupFactory'=> static function(MediaWikiServices $services):AggregateGroupMessageGroupFactory { return new AggregateGroupMessageGroupFactory($services->get( 'Translate:MessageGroupMetadata'));}, 'Translate:ConfigHelper'=> static function():ConfigHelper { return new ConfigHelper();}, 'Translate:CsvTranslationImporter'=> static function(MediaWikiServices $services):CsvTranslationImporter { return new CsvTranslationImporter( $services->getWikiPageFactory());}, 'Translate:EntitySearch'=> static function(MediaWikiServices $services):EntitySearch { return new EntitySearch($services->getMainWANObjectCache(), $services->getCollationFactory() ->makeCollation( 'uca-default-u-kn'), MessageGroups::singleton(), $services->getNamespaceInfo(), $services->get( 'Translate:MessageIndex'), $services->getTitleParser(), $services->getTitleFormatter());}, 'Translate:ExternalMessageSourceStateComparator'=> static function(MediaWikiServices $services):ExternalMessageSourceStateComparator { return new ExternalMessageSourceStateComparator(new SimpleStringComparator(), $services->getRevisionLookup(), $services->getPageStore());}, 'Translate:ExternalMessageSourceStateImporter'=> static function(MediaWikiServices $services):ExternalMessageSourceStateImporter { return new ExternalMessageSourceStateImporter($services->get( 'Translate:GroupSynchronizationCache'), $services->getJobQueueGroup(), LoggerFactory::getInstance(LogNames::GROUP_SYNCHRONIZATION), $services->get( 'Translate:MessageIndex'), $services->getTitleFactory(), $services->get( 'Translate:MessageGroupSubscription'), new ServiceOptions(ExternalMessageSourceStateImporter::CONSTRUCTOR_OPTIONS, $services->getMainConfig()));}, 'Translate:FileBasedMessageGroupFactory'=> static function(MediaWikiServices $services):FileBasedMessageGroupFactory { return new FileBasedMessageGroupFactory(new MessageGroupConfigurationParser(), new ServiceOptions(FileBasedMessageGroupFactory::SERVICE_OPTIONS, $services->getMainConfig()),);}, 'Translate:FileFormatFactory'=> static function(MediaWikiServices $services):FileFormatFactory { return new FileFormatFactory( $services->getObjectFactory());}, 'Translate:GroupSynchronizationCache'=> static function(MediaWikiServices $services):GroupSynchronizationCache { return new GroupSynchronizationCache( $services->get( 'Translate:PersistentCache'));}, 'Translate:HookDefinedMessageGroupFactory'=> static function(MediaWikiServices $services):HookDefinedMessageGroupFactory { return new HookDefinedMessageGroupFactory( $services->get( 'Translate:HookRunner'));}, 'Translate:HookRunner'=> static function(MediaWikiServices $services):HookRunner { return new HookRunner( $services->getHookContainer());}, 'Translate:MessageBundleDependencyPurger'=> static function(MediaWikiServices $services):MessageBundleDependencyPurger { return new MessageBundleDependencyPurger( $services->get( 'Translate:TranslatableBundleFactory'));}, 'Translate:MessageBundleMessageGroupFactory'=> static function(MediaWikiServices $services):MessageBundleMessageGroupFactory { return new MessageBundleMessageGroupFactory($services->get( 'Translate:MessageGroupMetadata'), new ServiceOptions(MessageBundleMessageGroupFactory::SERVICE_OPTIONS, $services->getMainConfig()),);}, 'Translate:MessageBundleStore'=> static function(MediaWikiServices $services):MessageBundleStore { return new MessageBundleStore($services->get( 'Translate:RevTagStore'), $services->getJobQueueGroup(), $services->getLanguageNameUtils(), $services->get( 'Translate:MessageIndex'), $services->get( 'Translate:MessageGroupMetadata'));}, 'Translate:MessageBundleTranslationLoader'=> static function(MediaWikiServices $services):MessageBundleTranslationLoader { return new MessageBundleTranslationLoader( $services->getLanguageFallback());}, 'Translate:MessageGroupMetadata'=> static function(MediaWikiServices $services):MessageGroupMetadata { return new MessageGroupMetadata( $services->getConnectionProvider());}, 'Translate:MessageGroupReviewStore'=> static function(MediaWikiServices $services):MessageGroupReviewStore { return new MessageGroupReviewStore($services->getConnectionProvider(), $services->get( 'Translate:HookRunner'));}, 'Translate:MessageGroupStatsTableFactory'=> static function(MediaWikiServices $services):MessageGroupStatsTableFactory { return new MessageGroupStatsTableFactory($services->get( 'Translate:ProgressStatsTableFactory'), $services->getLinkRenderer(), $services->get( 'Translate:MessageGroupReviewStore'), $services->get( 'Translate:MessageGroupMetadata'), $services->getMainConfig() ->get( 'TranslateWorkflowStates') !==false);}, 'Translate:MessageGroupSubscription'=> static function(MediaWikiServices $services):MessageGroupSubscription { return new MessageGroupSubscription($services->get( 'Translate:MessageGroupSubscriptionStore'), $services->getJobQueueGroup(), $services->getUserIdentityLookup(), LoggerFactory::getInstance(LogNames::GROUP_SUBSCRIPTION), new ServiceOptions(MessageGroupSubscription::CONSTRUCTOR_OPTIONS, $services->getMainConfig()));}, 'Translate:MessageGroupSubscriptionHookHandler'=> static function(MediaWikiServices $services):MessageGroupSubscriptionHookHandler { return new MessageGroupSubscriptionHookHandler($services->get( 'Translate:MessageGroupSubscription'), $services->getUserFactory());}, 'Translate:MessageGroupSubscriptionStore'=> static function(MediaWikiServices $services):MessageGroupSubscriptionStore { return new MessageGroupSubscriptionStore( $services->getConnectionProvider());}, 'Translate:MessageIndex'=> static function(MediaWikiServices $services):MessageIndex { $params=(array) $services->getMainConfig() ->get( 'TranslateMessageIndex');$class=array_shift( $params);$implementationMap=['HashMessageIndex'=> HashMessageIndex::class, 'CDBMessageIndex'=> CDBMessageIndex::class, 'DatabaseMessageIndex'=> DatabaseMessageIndex::class, 'hash'=> HashMessageIndex::class, 'cdb'=> CDBMessageIndex::class, 'database'=> DatabaseMessageIndex::class,];$messageIndexStoreClass=$implementationMap[$class] ?? $implementationMap['database'];return new MessageIndex(new $messageIndexStoreClass, $services->getMainWANObjectCache(), $services->getJobQueueGroup(), $services->get( 'Translate:HookRunner'), LoggerFactory::getInstance(LogNames::MAIN), $services->getMainObjectStash(), $services->getConnectionProvider(), new ServiceOptions(MessageIndex::SERVICE_OPTIONS, $services->getMainConfig()),);}, 'Translate:MessagePrefixStats'=> static function(MediaWikiServices $services):MessagePrefixStats { return new MessagePrefixStats( $services->getTitleParser());}, 'Translate:ParsingPlaceholderFactory'=> static function():ParsingPlaceholderFactory { return new ParsingPlaceholderFactory();}, 'Translate:PersistentCache'=> static function(MediaWikiServices $services):PersistentCache { return new PersistentDatabaseCache($services->getConnectionProvider(), $services->getJsonCodec());}, 'Translate:ProgressStatsTableFactory'=> static function(MediaWikiServices $services):ProgressStatsTableFactory { return new ProgressStatsTableFactory($services->getLinkRenderer(), $services->get( 'Translate:ConfigHelper'), $services->get( 'Translate:MessageGroupMetadata'));}, 'Translate:RevTagStore'=> static function(MediaWikiServices $services):RevTagStore { return new RevTagStore( $services->getConnectionProvider());}, 'Translate:SubpageListBuilder'=> static function(MediaWikiServices $services):SubpageListBuilder { return new SubpageListBuilder($services->get( 'Translate:TranslatableBundleFactory'), $services->getLinkBatchFactory());}, 'Translate:TranslatableBundleDeleter'=> static function(MediaWikiServices $services):TranslatableBundleDeleter { return new TranslatableBundleDeleter($services->getMainObjectStash(), $services->getJobQueueGroup(), $services->get( 'Translate:SubpageListBuilder'), $services->get( 'Translate:TranslatableBundleFactory'));}, 'Translate:TranslatableBundleExporter'=> static function(MediaWikiServices $services):TranslatableBundleExporter { return new TranslatableBundleExporter($services->get( 'Translate:SubpageListBuilder'), $services->getWikiExporterFactory(), $services->getConnectionProvider());}, 'Translate:TranslatableBundleFactory'=> static function(MediaWikiServices $services):TranslatableBundleFactory { return new TranslatableBundleFactory($services->get( 'Translate:TranslatablePageStore'), $services->get( 'Translate:MessageBundleStore'));}, 'Translate:TranslatableBundleImporter'=> static function(MediaWikiServices $services):TranslatableBundleImporter { return new TranslatableBundleImporter($services->getWikiImporterFactory(), $services->get( 'Translate:TranslatablePageParser'), $services->getRevisionLookup(), $services->getNamespaceInfo(), $services->getTitleFactory(), $services->getFormatterFactory());}, 'Translate:TranslatableBundleMover'=> static function(MediaWikiServices $services):TranslatableBundleMover { return new TranslatableBundleMover($services->getMovePageFactory(), $services->getJobQueueGroup(), $services->getLinkBatchFactory(), $services->get( 'Translate:TranslatableBundleFactory'), $services->get( 'Translate:SubpageListBuilder'), $services->getConnectionProvider(), $services->getObjectCacheFactory(), $services->getMainConfig() ->get( 'TranslatePageMoveLimit'));}, 'Translate:TranslatableBundleStatusStore'=> static function(MediaWikiServices $services):TranslatableBundleStatusStore { return new TranslatableBundleStatusStore($services->getConnectionProvider() ->getPrimaryDatabase(), $services->getCollationFactory() ->makeCollation( 'uca-default-u-kn'), $services->getDBLoadBalancer() ->getMaintenanceConnectionRef(DB_PRIMARY));}, 'Translate:TranslatablePageMarker'=> static function(MediaWikiServices $services):TranslatablePageMarker { return new TranslatablePageMarker($services->getConnectionProvider(), $services->getJobQueueGroup(), $services->getLinkRenderer(), MessageGroups::singleton(), $services->get( 'Translate:MessageIndex'), $services->getTitleFormatter(), $services->getTitleParser(), $services->get( 'Translate:TranslatablePageParser'), $services->get( 'Translate:TranslatablePageStore'), $services->get( 'Translate:TranslatablePageStateStore'), $services->get( 'Translate:TranslationUnitStoreFactory'), $services->get( 'Translate:MessageGroupMetadata'), $services->getWikiPageFactory(), $services->get( 'Translate:TranslatablePageView'), $services->get( 'Translate:MessageGroupSubscription'), $services->getFormatterFactory());}, 'Translate:TranslatablePageMessageGroupFactory'=> static function(MediaWikiServices $services):TranslatablePageMessageGroupFactory { return new TranslatablePageMessageGroupFactory(new ServiceOptions(TranslatablePageMessageGroupFactory::SERVICE_OPTIONS, $services->getMainConfig()),);}, 'Translate:TranslatablePageParser'=> static function(MediaWikiServices $services):TranslatablePageParser { return new TranslatablePageParser($services->get( 'Translate:ParsingPlaceholderFactory'));}, 'Translate:TranslatablePageStateStore'=> static function(MediaWikiServices $services):TranslatablePageStateStore { return new TranslatablePageStateStore($services->get( 'Translate:PersistentCache'), $services->getPageStore());}, 'Translate:TranslatablePageStore'=> static function(MediaWikiServices $services):TranslatablePageStore { return new TranslatablePageStore($services->get( 'Translate:MessageIndex'), $services->getJobQueueGroup(), $services->get( 'Translate:RevTagStore'), $services->getConnectionProvider(), $services->get( 'Translate:TranslatableBundleStatusStore'), $services->get( 'Translate:TranslatablePageParser'), $services->get( 'Translate:MessageGroupMetadata'));}, 'Translate:TranslatablePageView'=> static function(MediaWikiServices $services):TranslatablePageView { return new TranslatablePageView($services->getConnectionProvider(), $services->get( 'Translate:TranslatablePageStateStore'), new ServiceOptions(TranslatablePageView::SERVICE_OPTIONS, $services->getMainConfig()));}, 'Translate:TranslateSandbox'=> static function(MediaWikiServices $services):TranslateSandbox { return new TranslateSandbox($services->getUserFactory(), $services->getConnectionProvider(), $services->getPermissionManager(), $services->getAuthManager(), $services->getUserGroupManager(), $services->getActorStore(), $services->getUserOptionsManager(), $services->getJobQueueGroup(), $services->get( 'Translate:HookRunner'), new ServiceOptions(TranslateSandbox::CONSTRUCTOR_OPTIONS, $services->getMainConfig()));}, 'Translate:TranslationStashReader'=> static function(MediaWikiServices $services):TranslationStashReader { return new TranslationStashStorage( $services->getConnectionProvider() ->getPrimaryDatabase());}, 'Translate:TranslationStatsDataProvider'=> static function(MediaWikiServices $services):TranslationStatsDataProvider { return new TranslationStatsDataProvider(new ServiceOptions(TranslationStatsDataProvider::CONSTRUCTOR_OPTIONS, $services->getMainConfig()), $services->getObjectFactory(), $services->getConnectionProvider());}, 'Translate:TranslationUnitStoreFactory'=> static function(MediaWikiServices $services):TranslationUnitStoreFactory { return new TranslationUnitStoreFactory( $services->getDBLoadBalancer());}, 'Translate:TranslatorActivity'=> static function(MediaWikiServices $services):TranslatorActivity { $query=new TranslatorActivityQuery($services->getMainConfig(), $services->getDBLoadBalancer());return new TranslatorActivity($services->getMainObjectStash(), $query, $services->getJobQueueGroup());}, 'Translate:TtmServerFactory'=> static function(MediaWikiServices $services):TtmServerFactory { $config=$services->getMainConfig();$default=$config->get( 'TranslateTranslationDefaultService');if( $default===false) { $default=null;} return new TtmServerFactory( $config->get( 'TranslateTranslationServices'), $default);}]
@phpcs-require-sorted-array