-
Notifications
You must be signed in to change notification settings - Fork 837
Expand file tree
/
Copy pathi18n.ts
More file actions
873 lines (803 loc) · 29 KB
/
i18n.ts
File metadata and controls
873 lines (803 loc) · 29 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
import {
bucketTypeSchema,
I18nConfig,
localeCodeSchema,
resolveOverriddenLocale,
} from "@lingo.dev/_spec";
import { Command } from "interactive-commander";
import Z from "zod";
import _ from "lodash";
import * as path from "path";
import { getConfig } from "../utils/config";
import { getSettings } from "../utils/settings";
import {
ConfigError,
AuthenticationError,
ValidationError,
LocalizationError,
BucketProcessingError,
getCLIErrorType,
isLocalizationError,
isBucketProcessingError,
ErrorDetail,
aggregateErrorAnalytics,
createPreviousErrorContext,
} from "../utils/errors";
import Ora from "ora";
import createBucketLoader from "../loaders";
import { createAuthenticator } from "../utils/auth";
import { getBuckets } from "../utils/buckets";
import chalk from "chalk";
import { createTwoFilesPatch } from "diff";
import inquirer from "inquirer";
import externalEditor from "external-editor";
import updateGitignore from "../utils/update-gitignore";
import createProcessor from "../processor";
import { withExponentialBackoff } from "../utils/exp-backoff";
import trackEvent, { UserIdentity } from "../utils/observability";
import { createDeltaProcessor } from "../utils/delta";
export default new Command()
.command("i18n")
.description(
"DEPRECATED: Run localization pipeline (prefer `run` command instead)",
)
.helpOption("-h, --help", "Show help")
.option(
"--locale <locale>",
"Limit processing to the listed target locale codes from i18n.json. Repeat the flag to include multiple locales. Defaults to all configured target locales",
(val: string, prev: string[]) => (prev ? [...prev, val] : [val]),
)
.option(
"--bucket <bucket>",
"Limit processing to specific bucket types defined in i18n.json (e.g., json, yaml, android). Repeat the flag to include multiple bucket types. Defaults to all buckets",
(val: string, prev: string[]) => (prev ? [...prev, val] : [val]),
)
.option(
"--key <key>",
"Limit processing to a single translation key by exact match. Filters all buckets and locales to process only this key, useful for testing or debugging specific translations. Example: auth.login.title",
(val: string) => encodeURIComponent(val),
)
.option(
"--file [files...]",
"Filter processing to only buckets whose file paths contain these substrings. Example: 'components' to process only files in components directories",
)
.option(
"--frozen",
"Validate translations are up-to-date without making changes - fails if source files, target files, or lockfile are out of sync. Ideal for CI/CD to ensure translation consistency before deployment",
)
.option(
"--force",
"Force re-translation of all keys, bypassing change detection. Useful when you want to regenerate translations with updated AI models or translation settings",
)
.option(
"--verbose",
"Print the translation data being processed as formatted JSON for each bucket and locale",
)
.option(
"--interactive",
"Review and edit AI-generated translations interactively before applying changes to files",
)
.option(
"--api-key <api-key>",
"Override API key from settings or environment variables",
)
.option(
"--debug",
"Pause before processing localization so you can attach a debugger",
)
.option(
"--strict",
"Stop immediately on first error instead of continuing to process remaining buckets and locales (fail-fast mode)",
)
.action(async function (options) {
updateGitignore();
const ora = Ora();
// Show deprecation warning
console.log();
ora.warn(
chalk.yellow(
" DEPRECATED: 'i18n' is deprecated. Please use 'run' instead. Docs: https://lingo.dev/cli/commands/run",
),
);
console.log();
let flags: ReturnType<typeof parseFlags>;
try {
flags = parseFlags(options);
} catch (parseError: any) {
// Handle flag validation errors (like invalid locale codes)
await trackEvent(null, "cmd.i18n.error", {
errorType: "validation_error",
errorName: parseError.name || "ValidationError",
errorMessage: parseError.message || "Invalid command line options",
errorStack: parseError.stack,
fatal: true,
errorCount: 1,
stage: "flag_validation",
});
await new Promise((resolve) => setTimeout(resolve, 50));
throw parseError;
}
if (flags.debug) {
// wait for user input, use inquirer
const { debug } = await inquirer.prompt([
{
type: "confirm",
name: "debug",
message: "Debug mode. Wait for user input before continuing.",
},
]);
}
let hasErrors = false;
let userIdentity: UserIdentity = null;
const errorDetails: ErrorDetail[] = [];
try {
ora.start("Loading configuration...");
const i18nConfig = getConfig();
const settings = getSettings(flags.apiKey);
ora.succeed("Configuration loaded");
ora.start("Validating localization configuration...");
validateParams(i18nConfig, flags);
ora.succeed("Localization configuration is valid");
ora.start("Connecting to Lingo.dev Localization Engine...");
const isByokMode = !!i18nConfig?.provider;
if (isByokMode) {
userIdentity = null;
ora.succeed("Using external provider (BYOK mode)");
} else {
const auth = await validateAuth(settings);
userIdentity = { email: auth.email, id: auth.id };
ora.succeed(`Authenticated as ${auth.email}`);
}
await trackEvent(userIdentity, "cmd.i18n.start", {
i18nConfig,
flags,
});
let buckets = getBuckets(i18nConfig!);
if (flags.bucket?.length) {
buckets = buckets.filter((bucket: any) =>
flags.bucket!.includes(bucket.type),
);
}
ora.succeed("Buckets retrieved");
if (flags.file?.length) {
buckets = buckets
.map((bucket: any) => {
const paths = bucket.paths.filter((path: any) =>
flags.file!.find((file) => path.pathPattern?.includes(file)),
);
return { ...bucket, paths };
})
.filter((bucket: any) => bucket.paths.length > 0);
if (buckets.length === 0) {
ora.fail(
"No buckets found. All buckets were filtered out by --file option.",
);
throw new Error(
"No buckets found. All buckets were filtered out by --file option.",
);
} else {
ora.info(`\x1b[36mProcessing only filtered buckets:\x1b[0m`);
buckets.map((bucket: any) => {
ora.info(` ${bucket.type}:`);
bucket.paths.forEach((path: any) => {
ora.info(` - ${path.pathPattern}`);
});
});
}
}
const targetLocales = flags.locale?.length
? flags.locale
: i18nConfig!.locale.targets;
// Ensure the lockfile exists
ora.start("Setting up localization cache...");
const checkLockfileProcessor = createDeltaProcessor("");
const lockfileExists = await checkLockfileProcessor.checkIfLockExists();
if (!lockfileExists) {
ora.start("Creating i18n.lock...");
for (const bucket of buckets) {
for (const bucketPath of bucket.paths) {
const sourceLocale = resolveOverriddenLocale(
i18nConfig!.locale.source,
bucketPath.delimiter,
);
const bucketLoader = createBucketLoader(
bucket.type,
bucketPath.pathPattern,
{
defaultLocale: sourceLocale,
injectLocale: bucket.injectLocale,
formatter: i18nConfig!.formatter,
},
bucket.lockedKeys,
bucket.lockedPatterns,
bucket.ignoredKeys,
bucket.preservedKeys,
bucket.localizableKeys,
);
bucketLoader.setDefaultLocale(sourceLocale);
await bucketLoader.init();
const sourceData = await bucketLoader.pull(
i18nConfig!.locale.source,
);
const deltaProcessor = createDeltaProcessor(bucketPath.pathPattern);
const checksums = await deltaProcessor.createChecksums(sourceData);
await deltaProcessor.saveChecksums(checksums);
}
}
ora.succeed("Localization cache initialized");
} else {
ora.succeed("Localization cache loaded");
}
if (flags.frozen) {
ora.start("Checking for lockfile updates...");
let requiresUpdate: string | null = null;
bucketLoop: for (const bucket of buckets) {
for (const bucketPath of bucket.paths) {
const sourceLocale = resolveOverriddenLocale(
i18nConfig!.locale.source,
bucketPath.delimiter,
);
const bucketLoader = createBucketLoader(
bucket.type,
bucketPath.pathPattern,
{
defaultLocale: sourceLocale,
returnUnlocalizedKeys: true,
injectLocale: bucket.injectLocale,
},
bucket.lockedKeys,
bucket.lockedPatterns,
bucket.ignoredKeys,
bucket.preservedKeys,
bucket.localizableKeys,
);
bucketLoader.setDefaultLocale(sourceLocale);
await bucketLoader.init();
const { unlocalizable: sourceUnlocalizable, ...sourceData } =
await bucketLoader.pull(i18nConfig!.locale.source);
const deltaProcessor = createDeltaProcessor(bucketPath.pathPattern);
const sourceChecksums =
await deltaProcessor.createChecksums(sourceData);
const savedChecksums = await deltaProcessor.loadChecksums();
// Get updated data by comparing current checksums with saved checksums
const updatedSourceData = _.pickBy(
sourceData,
(value, key) => sourceChecksums[key] !== savedChecksums[key],
);
// translation was updated in the source file
if (Object.keys(updatedSourceData).length > 0) {
requiresUpdate = "updated";
break bucketLoop;
}
for (const _targetLocale of targetLocales) {
const targetLocale = resolveOverriddenLocale(
_targetLocale,
bucketPath.delimiter,
);
const { unlocalizable: targetUnlocalizable, ...targetData } =
await bucketLoader.pull(targetLocale);
const missingKeys = _.difference(
Object.keys(sourceData),
Object.keys(targetData),
);
const extraKeys = _.difference(
Object.keys(targetData),
Object.keys(sourceData),
);
const unlocalizableDataDiff = !_.isEqual(
sourceUnlocalizable,
targetUnlocalizable,
);
// translation is missing in the target file
if (missingKeys.length > 0) {
requiresUpdate = "missing";
break bucketLoop;
}
// target file has extra translations
if (extraKeys.length > 0) {
requiresUpdate = "extra";
break bucketLoop;
}
// unlocalizable keys do not match
if (unlocalizableDataDiff) {
requiresUpdate = "unlocalizable";
break bucketLoop;
}
}
}
}
if (requiresUpdate) {
const message = {
updated: "Source file has been updated.",
missing: "Target file is missing translations.",
extra:
"Target file has extra translations not present in the source file.",
unlocalizable:
"Unlocalizable data (such as booleans, dates, URLs, etc.) do not match.",
}[requiresUpdate];
ora.fail(
`Localization data has changed; please update i18n.lock or run without --frozen.`,
);
ora.fail(` Details: ${message}`);
throw new Error(
`Localization data has changed; please update i18n.lock or run without --frozen. Details: ${message}`,
);
} else {
ora.succeed("No lockfile updates required.");
}
}
// Process each bucket
for (const bucket of buckets) {
try {
console.log();
ora.info(`Processing bucket: ${bucket.type}`);
for (const bucketPath of bucket.paths) {
const bucketOra = Ora({ indent: 2 }).info(
`Processing path: ${bucketPath.pathPattern}`,
);
const sourceLocale = resolveOverriddenLocale(
i18nConfig!.locale.source,
bucketPath.delimiter,
);
const bucketLoader = createBucketLoader(
bucket.type,
bucketPath.pathPattern,
{
defaultLocale: sourceLocale,
injectLocale: bucket.injectLocale,
formatter: i18nConfig!.formatter,
},
bucket.lockedKeys,
bucket.lockedPatterns,
bucket.ignoredKeys,
bucket.preservedKeys,
bucket.localizableKeys,
);
bucketLoader.setDefaultLocale(sourceLocale);
await bucketLoader.init();
let sourceData = await bucketLoader.pull(sourceLocale);
for (const _targetLocale of targetLocales) {
const targetLocale = resolveOverriddenLocale(
_targetLocale,
bucketPath.delimiter,
);
try {
bucketOra.start(
`[${sourceLocale} -> ${targetLocale}] (0%) Localization in progress...`,
);
sourceData = await bucketLoader.pull(sourceLocale);
const targetData = await bucketLoader.pull(targetLocale);
const deltaProcessor = createDeltaProcessor(
bucketPath.pathPattern,
);
const checksums = await deltaProcessor.loadChecksums();
const delta = await deltaProcessor.calculateDelta({
sourceData,
targetData,
checksums,
});
let processableData = _.chain(sourceData)
.entries()
.filter(
([key, value]) =>
delta.added.includes(key) ||
delta.updated.includes(key) ||
!!flags.force,
)
.fromPairs()
.value();
if (flags.key) {
processableData = _.pickBy(
processableData,
(_, key) => key === flags.key,
);
}
if (flags.verbose) {
bucketOra.info(JSON.stringify(processableData, null, 2));
}
bucketOra.start(
`[${sourceLocale} -> ${targetLocale}] [${
Object.keys(processableData).length
} entries] (0%) AI localization in progress...`,
);
let processPayload = createProcessor(i18nConfig!.provider, {
apiKey: settings.auth.apiKey,
apiUrl: settings.auth.apiUrl,
engineId: i18nConfig!.engineId,
});
processPayload = withExponentialBackoff(
processPayload,
3,
1000,
);
const processedTargetData = await processPayload(
{
sourceLocale,
sourceData,
processableData,
targetLocale,
// When --force is used, exclude previous translations from reference to ensure fresh translations
targetData: flags.force ? {} : targetData,
},
(progress, sourceChunk, processedChunk) => {
bucketOra.text = `[${sourceLocale} -> ${targetLocale}] [${
Object.keys(processableData).length
} entries] (${progress}%) AI localization in progress...`;
},
);
if (flags.verbose) {
bucketOra.info(JSON.stringify(processedTargetData, null, 2));
}
let finalTargetData = _.merge(
{},
sourceData,
targetData,
processedTargetData,
);
// rename keys
finalTargetData = _.chain(finalTargetData)
.entries()
.map(([key, value]) => {
const renaming = delta.renamed.find(
([oldKey, newKey]) => oldKey === key,
);
if (!renaming) {
return [key, value];
}
return [renaming[1], value];
})
.fromPairs()
.value();
if (flags.interactive) {
bucketOra.stop();
const reviewedData = await reviewChanges({
pathPattern: bucketPath.pathPattern,
targetLocale,
currentData: targetData,
proposedData: finalTargetData,
sourceData,
force: flags.force!,
});
finalTargetData = reviewedData;
bucketOra.start(
`Applying changes to ${bucketPath} (${targetLocale})`,
);
}
const finalDiffSize = _.chain(finalTargetData)
.omitBy((value, key) => {
const targetValue = targetData[key];
// For objects (like plural variations), use deep equality
// For primitives (strings, numbers), use strict equality
if (typeof value === "object" && value !== null) {
return _.isEqual(value, targetValue);
}
return value === targetValue;
})
.size()
.value();
// Push to bucket all the time as there might be changes to unlocalizable keys
await bucketLoader.push(targetLocale, finalTargetData);
if (finalDiffSize > 0 || flags.force) {
bucketOra.succeed(
`[${sourceLocale} -> ${targetLocale}] Localization completed`,
);
} else {
bucketOra.succeed(
`[${sourceLocale} -> ${targetLocale}] Localization completed (no changes).`,
);
}
} catch (_error: any) {
const error = new LocalizationError(
`[${sourceLocale} -> ${targetLocale}] Localization failed: ${_error.message}`,
{
bucket: bucket.type,
sourceLocale,
targetLocale,
pathPattern: bucketPath.pathPattern,
},
);
errorDetails.push({
type: "locale_error",
bucket: bucket.type,
locale: `${sourceLocale} -> ${targetLocale}`,
pathPattern: bucketPath.pathPattern,
message: _error.message,
stack: _error.stack,
});
if (flags.strict) {
throw error;
} else {
bucketOra.fail(error.message);
hasErrors = true;
}
}
}
const deltaProcessor = createDeltaProcessor(bucketPath.pathPattern);
const checksums = await deltaProcessor.createChecksums(sourceData);
if (!flags.locale?.length) {
await deltaProcessor.saveChecksums(checksums);
}
}
} catch (_error: any) {
const error = new BucketProcessingError(
`Failed to process bucket ${bucket.type}: ${_error.message}`,
bucket.type,
);
errorDetails.push({
type: "bucket_error",
bucket: bucket.type,
message: _error.message,
stack: _error.stack,
});
if (flags.strict) {
throw error;
} else {
ora.fail(error.message);
hasErrors = true;
}
}
}
console.log();
if (!hasErrors) {
ora.succeed("Localization completed.");
await trackEvent(userIdentity, "cmd.i18n.success", {
i18nConfig: {
sourceLocale: i18nConfig!.locale.source,
targetLocales: i18nConfig!.locale.targets,
bucketTypes: Object.keys(i18nConfig!.buckets),
},
flags,
bucketCount: buckets.length,
localeCount: targetLocales.length,
processedSuccessfully: true,
});
await new Promise((resolve) => setTimeout(resolve, 50));
} else {
ora.warn("Localization completed with errors.");
process.exitCode = 1;
await trackEvent(userIdentity, "cmd.i18n.error", {
flags,
...aggregateErrorAnalytics(
errorDetails,
buckets,
targetLocales,
i18nConfig!,
),
});
await new Promise((resolve) => setTimeout(resolve, 50));
}
} catch (error: any) {
ora.fail(error.message);
// Use robust error type detection
const errorType = getCLIErrorType(error);
// Extract additional context from typed errors
let errorContext: any = {};
if (isLocalizationError(error)) {
errorContext = {
bucket: error.bucket,
sourceLocale: error.sourceLocale,
targetLocale: error.targetLocale,
pathPattern: error.pathPattern,
};
} else if (isBucketProcessingError(error)) {
errorContext = {
bucket: error.bucket,
};
}
await trackEvent(userIdentity, "cmd.i18n.error", {
flags,
errorType,
errorName: error.name || "Error",
errorMessage: error.message,
errorStack: error.stack,
errorContext,
fatal: true,
errorCount: errorDetails.length + 1,
previousErrors: createPreviousErrorContext(errorDetails),
});
await new Promise((resolve) => setTimeout(resolve, 50));
}
});
function parseFlags(options: any) {
return Z.object({
apiKey: Z.string().optional(),
locale: Z.array(localeCodeSchema).optional(),
bucket: Z.array(bucketTypeSchema).optional(),
force: Z.boolean().optional(),
frozen: Z.boolean().optional(),
verbose: Z.boolean().optional(),
strict: Z.boolean().optional(),
key: Z.string().optional(),
file: Z.array(Z.string()).optional(),
interactive: Z.boolean().prefault(false),
debug: Z.boolean().prefault(false),
}).parse(options);
}
// Export validateAuth for use in other commands
export async function validateAuth(settings: ReturnType<typeof getSettings>) {
if (!settings.auth.apiKey) {
throw new AuthenticationError({
message:
"Not authenticated. Please run `lingo.dev login` to authenticate.",
docUrl: "authError",
});
}
const authenticator = createAuthenticator({
apiKey: settings.auth.apiKey,
apiUrl: settings.auth.apiUrl,
});
const user = await authenticator.whoami();
if (!user) {
throw new AuthenticationError({
message: "Invalid API key. Please run `lingo.dev login` to authenticate.",
docUrl: "authError",
});
}
return user;
}
function validateParams(
i18nConfig: I18nConfig | null,
flags: ReturnType<typeof parseFlags>,
) {
if (!i18nConfig) {
throw new ConfigError({
message:
"i18n.json not found. Please run `lingo.dev init` to initialize the project.",
docUrl: "i18nNotFound",
});
} else if (!i18nConfig.buckets || !Object.keys(i18nConfig.buckets).length) {
throw new ConfigError({
message:
"No buckets found in i18n.json. Please add at least one bucket containing i18n content.",
docUrl: "bucketNotFound",
});
} else if (
flags.locale?.some((locale) => !i18nConfig.locale.targets.includes(locale))
) {
throw new ValidationError({
message: `One or more specified locales do not exist in i18n.json locale.targets. Please add them to the list and try again.`,
docUrl: "localeTargetNotFound",
});
} else if (
flags.bucket?.some(
(bucket) =>
!i18nConfig.buckets[bucket as keyof typeof i18nConfig.buckets],
)
) {
throw new ValidationError({
message: `One or more specified buckets do not exist in i18n.json. Please add them to the list and try again.`,
docUrl: "bucketNotFound",
});
}
}
async function reviewChanges(args: {
pathPattern: string;
targetLocale: string;
currentData: Record<string, any>;
proposedData: Record<string, any>;
sourceData: Record<string, any>;
force: boolean;
}): Promise<Record<string, any>> {
const currentStr = JSON.stringify(args.currentData, null, 2);
const proposedStr = JSON.stringify(args.proposedData, null, 2);
// Early return if no changes
if (currentStr === proposedStr && !args.force) {
console.log(
`\n${chalk.blue(args.pathPattern)} (${chalk.yellow(
args.targetLocale,
)}): ${chalk.gray("No changes to review")}`,
);
return args.proposedData;
}
const patch = createTwoFilesPatch(
`${args.pathPattern} (current)`,
`${args.pathPattern} (proposed)`,
currentStr,
proposedStr,
undefined,
undefined,
{ context: 3 },
);
// Color the diff output
const coloredDiff = patch
.split("\n")
.map((line) => {
if (line.startsWith("+")) return chalk.green(line);
if (line.startsWith("-")) return chalk.red(line);
if (line.startsWith("@")) return chalk.cyan(line);
return line;
})
.join("\n");
console.log(
`\nReviewing changes for ${chalk.blue(args.pathPattern)} (${chalk.yellow(
args.targetLocale,
)}):`,
);
console.log(coloredDiff);
const { action } = await inquirer.prompt([
{
type: "list",
name: "action",
message: "Choose action:",
choices: [
{ name: "Approve changes", value: "approve" },
{ name: "Skip changes", value: "skip" },
{ name: "Edit individually", value: "edit" },
],
default: "approve",
},
]);
if (action === "approve") {
return args.proposedData;
}
if (action === "skip") {
return args.currentData;
}
// If edit was chosen, prompt for each changed value
const customData = { ...args.currentData };
const changes = _.reduce(
args.proposedData,
(result: string[], value: string, key: string) => {
if (args.currentData[key] !== value) {
result.push(key);
}
return result;
},
[],
);
for (const key of changes) {
console.log(`\nEditing value for: ${chalk.cyan(key)}`);
console.log(chalk.gray("Source text:"), chalk.blue(args.sourceData[key]));
console.log(
chalk.gray("Current value:"),
chalk.red(args.currentData[key] || "(empty)"),
);
console.log(
chalk.gray("Suggested value:"),
chalk.green(args.proposedData[key]),
);
console.log(
chalk.gray(
"\nYour editor will open. Edit the text and save to continue.",
),
);
console.log(chalk.gray("------------"));
try {
// Prepare the editor content with a header comment and the suggested value
const editorContent = [
"# Edit the translation below.",
"# Lines starting with # will be ignored.",
"# Save and exit the editor to continue.",
"#",
`# Source text (${chalk.blue("English")}):`,
`# ${args.sourceData[key]}`,
"#",
`# Current value (${chalk.red(args.targetLocale)}):`,
`# ${args.currentData[key] || "(empty)"}`,
"#",
args.proposedData[key],
].join("\n");
const result = externalEditor.edit(editorContent);
// Clean up the result by removing comments and trimming
const customValue = result
.split("\n")
.filter((line) => !line.startsWith("#"))
.join("\n")
.trim();
if (customValue) {
customData[key] = customValue;
} else {
console.log(
chalk.yellow("Empty value provided, keeping the current value."),
);
customData[key] = args.currentData[key] || args.proposedData[key];
}
} catch (error) {
console.log(
chalk.red("Error while editing, keeping the suggested value."),
);
customData[key] = args.proposedData[key];
}
}
return customData;
}