summaryrefslogtreecommitdiff
blob: 023734023922c6e5ed054885a01a64cf966aba92 (plain)
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
<?php
declare( strict_types = 1 );

namespace MediaWiki\Extension\Translate\Synchronization;

use FileBasedMessageGroup;
use JsonFFS;
use MediaWiki\Extension\Translate\Utilities\BaseMaintenanceScript;
use MediaWiki\Logger\LoggerFactory;
use MessageGroups;
use RuntimeException;
use SimpleFFS;
use TranslateUtils;

/**
 * Script to backport translations from one branch to another.
 *
 * @since 2021.05
 * @license GPL-2.0-or-later
 * @author Niklas Laxström
 */
class BackportTranslationsMaintenanceScript extends BaseMaintenanceScript {
	public function __construct() {
		parent::__construct();
		$this->addDescription( 'Backport translations from one branch to another.' );

		$this->addOption(
			'group',
			'Comma separated list of message group IDs (supports * wildcard) to backport',
			self::REQUIRED,
			self::HAS_ARG
		);
		$this->addOption(
			'source-path',
			'Source path for reading updated translations. Defaults to $wgTranslateGroupRoot.',
			self::OPTIONAL,
			self::HAS_ARG
		);
		$this->addOption(
			'target-path',
			'Target path for writing backported translations',
			self::REQUIRED,
			self::HAS_ARG
		);
		$this->addOption(
			'filter-path',
			'Only export a group if its export path matches this prefix (relative to target-path)',
			self::OPTIONAL,
			self::HAS_ARG
		);
		$this->addOption(
			'never-export-languages',
			'Languages to not export',
			self::OPTIONAL,
			self::HAS_ARG
		);
		$this->requireExtension( 'Translate' );
	}

	/** @inheritDoc */
	public function execute() {
		$config = $this->getConfig();
		$logger = LoggerFactory::getInstance( 'Translate.GroupSynchronization' );
		$groupPattern = $this->getOption( 'group' ) ?? '';
		$logger->info(
			'Starting backports for groups {groups}',
			[ 'groups' => $groupPattern ]
		);

		$sourcePath = $this->getOption( 'source-path' ) ?: $config->get( 'TranslateGroupRoot' );
		if ( !is_readable( $sourcePath ) ) {
			$this->fatalError( "Source directory is not readable ($sourcePath)." );
		}

		$targetPath = $this->getOption( 'target-path' );
		if ( !is_writable( $targetPath ) ) {
			$this->fatalError( "Target directory is not writable ($targetPath)." );
		}

		$groupIds = MessageGroups::expandWildcards( explode( ',', trim( $groupPattern ) ) );
		$groups = MessageGroups::getGroupsById( $groupIds );
		if ( $groups === [] ) {
			$this->fatalError( "Pattern $groupPattern did not match any message groups." );
		}

		$neverExportLanguages = $this->csv2array(
			$this->getOption( 'never-export-languages' ) ?? ''
		);
		$supportedLanguages = TranslateUtils::getLanguageNames( 'en' );

		foreach ( $groups as $group ) {
			$groupId = $group->getId();
			if ( !$group instanceof FileBasedMessageGroup ) {
				if ( !$this->hasOption( 'filter-path' ) ) {
					$this->error( "Skipping $groupId: Not instance of FileBasedMessageGroup" );
				}
				continue;
			}

			if ( !$group->getFFS() instanceof JsonFFS ) {
				$this->error( "Skipping $groupId: Only JSON format is supported" );
				continue;
			}

			if ( $this->hasOption( 'filter-path' ) ) {
				$filter = $this->getOption( 'filter-path' );
				$exportPath = $group->getTargetFilename( '*' );
				if ( !$this->matchPath( $filter, $exportPath ) ) {
					continue;
				}
			}

			/** @var FileBasedMessageGroup $group */
			$sourceLanguage = $group->getSourceLanguage();
			try {
				$sourceDefinitions = $this->loadDefinitions( $group, $sourcePath, $sourceLanguage );
				$targetDefinitions = $this->loadDefinitions( $group, $targetPath, $sourceLanguage );
			} catch ( RuntimeException $e ) {
				$this->output(
					"Skipping $groupId: Error while loading definitions: {$e->getMessage()}\n"
				);
				continue;
			}

			$keyCompatibilityMap = $this->getKeyCompatibilityMap(
				$sourceDefinitions['MESSAGES'],
				$targetDefinitions['MESSAGES'],
				$group->getFFS()
			);

			if ( array_filter( $keyCompatibilityMap ) === [] ) {
				$this->output( "Skipping $groupId: No compatible keys found\n" );
				continue;
			}

			$summary = [];
			$languages = array_keys( $group->getTranslatableLanguages() ?? $supportedLanguages );
			$languagesToSkip = $neverExportLanguages;
			$languagesToSkip[] = $sourceLanguage;
			$languages = array_diff( $languages, $languagesToSkip );

			foreach ( $languages as $language ) {
				$status = $this->backport(
					$group,
					$sourcePath,
					$targetPath,
					$keyCompatibilityMap,
					$language
				);

				$summary[$status][] = $language;
			}

			$numUpdated = count( $summary[ 'updated' ] ?? [] );
			$numAdded = count( $summary[ 'new' ] ?? [] );
			if ( ( $numUpdated + $numAdded ) > 0 ) {
				$this->output(
					sprintf(
						"%s: Compatible keys: %d. Updated %d languages, %d new (%s)\n",
						$group->getId(),
						count( $keyCompatibilityMap ),
						$numUpdated,
						$numAdded,
						implode( ', ', $summary[ 'new' ] ?? [] )
					)
				);
			}
		}
	}

	private function csv2array( string $input ): array {
		return array_filter(
			array_map( 'trim', explode( ',', $input ) ),
			static function ( $v ) {
				return $v !== '';
			}
		);
	}

	private function matchPath( string $prefix, string $full ): bool {
		$prefix = "./$prefix";
		$length = strlen( $prefix );
		return substr( $full, 0, $length ) === $prefix;
	}

	private function loadDefinitions(
		FileBasedMessageGroup $group,
		string $path,
		string $language
	): array {
		$file = $path . '/' . $group->getTargetFilename( $language );

		if ( !file_exists( $file ) ) {
			throw new RuntimeException( "File $file does not exist" );
		}

		$contents = file_get_contents( $file );
		return $group->getFFS()->readFromVariable( $contents );
	}

	/**
	 * Compares two arrays and returns a new array with keys from the target array with associated values
	 * being a boolean indicating whether the source array value is compatible with the target array value.
	 *
	 * Target array key order was chosen because in backporting we want to use the order of keys in the
	 * backport target (stable branch). Comparison is done with SimpleFFS::isContentEqual.
	 *
	 * @return array<string,bool> Keys in target order
	 */
	private function getKeyCompatibilityMap( array $source, array $target, SimpleFFS $ffs ): array {
		$keys = [];
		foreach ( $target as $key => $value ) {
			$keys[$key] = isset( $source[ $key ] ) && $ffs->isContentEqual( $source[ $key ], $value );
		}
		return $keys;
	}

	private function backport(
		FileBasedMessageGroup $group,
		string $source,
		string $targetPath,
		array $keyCompatibilityMap,
		string $language
	): string {
		try {
			$sourceTemplate = $this->loadDefinitions( $group, $source, $language );
		} catch ( RuntimeException $e ) {
			return 'no definitions';
		}

		try {
			$targetTemplate = $this->loadDefinitions( $group, $targetPath, $language );
		} catch ( RuntimeException $e ) {
			$targetTemplate = [
				'MESSAGES' => [],
				'AUTHORS' => [],
			];
		}

		// Amend the target with compatible things from the source
		$hasUpdates = false;

		$ffs = $group->getFFS();

		// This has been checked before, but checking again to keep Phan and IDEs happy.
		// Remove once support for other FFS are added.
		if ( !$ffs instanceof JsonFFS ) {
			throw new RuntimeException(
				"Expected FFS type: " . JsonFFS::class . '; got: ' . get_class( $ffs )
			);
		}

		$combinedMessages = [];
		// $keyCompatibilityMap has the target (stable branch) source language key order
		foreach ( $keyCompatibilityMap as $key => $isCompatible ) {
			$sourceValue = $sourceTemplate['MESSAGES'][$key] ?? null;
			$targetValue = $targetTemplate['MESSAGES'][$key] ?? null;

			// Use existing translation value from the target (stable branch) as the default
			if ( $targetValue !== null ) {
				$combinedMessages[$key] = $targetValue;
			}

			// If the source (development branch) has a different translation for a compatible key
			// replace the target (stable branch) translation with it.
			if ( !$isCompatible ) {
				continue;
			}
			if ( $sourceValue !== null && !$ffs->isContentEqual( $sourceValue, $targetValue ) ) {
				// Keep track if we actually overwrote any values, so we can report back stats
				$hasUpdates = true;
				$combinedMessages[$key] = $sourceValue;
			}
		}

		if ( !$hasUpdates ) {
			return 'no updates';
		}

		// Copy over all authors (we do not know per-message level)
		$combinedAuthors = array_merge(
			$targetTemplate[ 'AUTHORS' ] ?? [],
			$sourceTemplate[ 'AUTHORS' ] ?? []
		);
		$combinedAuthors = array_unique( $combinedAuthors );
		$combinedAuthors = $ffs->filterAuthors( $combinedAuthors, $language );

		$targetTemplate['AUTHORS'] = $combinedAuthors;
		$targetTemplate['MESSAGES'] = $combinedMessages;

		$backportedContent = $ffs->generateFile( $targetTemplate );

		$targetFilename = $targetPath . '/' . $group->getTargetFilename( $language );
		if ( file_exists( $targetFilename ) ) {
			$currentContent = file_get_contents( $targetFilename );

			if ( $ffs->shouldOverwrite( $currentContent, $backportedContent ) ) {
				file_put_contents( $targetFilename, $backportedContent );
			}
			return 'updated';
		} else {
			file_put_contents( $targetFilename, $backportedContent );
			return 'new';
		}
	}
}