-
Notifications
You must be signed in to change notification settings - Fork 363
/
catalog.ts
359 lines (311 loc) 路 9.77 KB
/
catalog.ts
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
import fs from "fs"
import path from "path"
import * as R from "ramda"
import glob from "glob"
import normalize from "normalize-path"
import { LinguiConfigNormalized, OrderBy } from "@lingui/conf"
import { FormatterWrapper } from "./formats"
import { CliExtractOptions } from "../lingui-extract"
import { CliExtractTemplateOptions } from "../lingui-extract-template"
import { CompiledCatalogNamespace } from "./compile"
import {
getTranslationsForCatalog,
GetTranslationsOptions,
} from "./catalog/getTranslationsForCatalog"
import { mergeCatalog } from "./catalog/mergeCatalog"
import { extractFromFiles } from "./catalog/extractFromFiles"
import {
isDirectory,
normalizeRelativePath,
replacePlaceholders,
writeFile,
} from "./utils"
import {
AllCatalogsType,
CatalogType,
ExtractedCatalogType,
ExtractedMessageType,
} from "./types"
const LOCALE = "{locale}"
const LOCALE_SUFFIX_RE = /\{locale\}.*$/
export type MakeOptions = CliExtractOptions & {
orderBy?: OrderBy
}
export type MakeTemplateOptions = CliExtractTemplateOptions & {
orderBy?: OrderBy
}
export type MergeOptions = {
overwrite?: boolean
files?: string[]
}
export type CatalogProps = {
name?: string
path: string
include: Array<string>
exclude?: Array<string>
templatePath?: string
format: FormatterWrapper
}
export class Catalog {
name?: string
path: string
include: Array<string>
exclude: Array<string>
format: FormatterWrapper
templateFile?: string
constructor(
{ name, path, include, templatePath, format, exclude = [] }: CatalogProps,
public config: LinguiConfigNormalized
) {
this.name = name
this.path = normalizeRelativePath(path)
this.include = include.map(normalizeRelativePath)
this.exclude = [this.localeDir, ...exclude.map(normalizeRelativePath)]
this.format = format
this.templateFile =
templatePath ||
getTemplatePath(this.format.getTemplateExtension(), this.path)
}
getFilename(locale: string): string {
return (
replacePlaceholders(this.path, { locale }) +
this.format.getCatalogExtension()
)
}
async make(options: MakeOptions): Promise<AllCatalogsType | false> {
const nextCatalog = await this.collect({ files: options.files })
if (!nextCatalog) return false
const prevCatalogs = await this.readAll()
const catalogs = this.merge(prevCatalogs, nextCatalog, {
overwrite: options.overwrite,
files: options.files,
})
// Map over all locales and post-process each catalog
const cleanAndSort = R.map(
R.pipe(
// Clean obsolete messages
(options.clean ? cleanObsolete : R.identity) as any,
// Sort messages
order(options.orderBy)
)
) as unknown as (catalog: AllCatalogsType) => AllCatalogsType
const sortedCatalogs = cleanAndSort(catalogs)
const locales = options.locale ? options.locale : this.locales
await Promise.all(
locales.map((locale) => this.write(locale, sortedCatalogs[locale]))
)
return sortedCatalogs
}
async makeTemplate(
options: MakeTemplateOptions
): Promise<CatalogType | false> {
const catalog = await this.collect({ files: options.files })
if (!catalog) return false
const sorted = order<CatalogType>(options.orderBy)(catalog as CatalogType)
await this.writeTemplate(sorted)
return sorted
}
/**
* Collect messages from source paths. Return a raw message catalog as JSON.
*/
async collect(
options: { files?: string[] } = {}
): Promise<ExtractedCatalogType | undefined> {
let paths = this.sourcePaths
if (options.files) {
options.files = options.files.map((p) => normalize(p, false))
const regex = new RegExp(options.files.join("|"), "i")
paths = paths.filter((path: string) => regex.test(path))
}
return await extractFromFiles(paths, this.config)
}
/*
*
* prevCatalogs - map of message catalogs in all available languages with translations
* nextCatalog - language-agnostic catalog with collected messages
*
* Note: if a catalog in prevCatalogs is null it means the language is available, but
* no previous catalog was generated (usually first run).
*
* Orthogonal use-cases
* --------------------
*
* Message IDs:
* - auto-generated IDs: message is used as a key, `defaults` is not set
* - custom IDs: message is used as `defaults`, custom ID as a key
*
* Source locale (defined by `sourceLocale` in config):
* - catalog for `sourceLocale`: initially, `translation` is prefilled with `defaults`
* (for custom IDs) or `key` (for auto-generated IDs)
* - all other languages: translation is kept empty
*/
merge(
prevCatalogs: AllCatalogsType,
nextCatalog: ExtractedCatalogType,
options: MergeOptions
) {
return R.mapObjIndexed((prevCatalog, locale) => {
return mergeCatalog(
prevCatalog,
nextCatalog,
this.config.sourceLocale === locale,
options
)
}, prevCatalogs)
}
async getTranslations(locale: string, options: GetTranslationsOptions) {
return await getTranslationsForCatalog(this, locale, options)
}
async write(
locale: string,
messages: CatalogType
): Promise<[created: boolean, filename: string]> {
const filename = this.getFilename(locale)
const created = !fs.existsSync(filename)
await this.format.write(filename, messages, locale)
return [created, filename]
}
async writeTemplate(messages: CatalogType): Promise<void> {
const filename = this.templateFile
await this.format.write(filename, messages, undefined)
}
async writeCompiled(
locale: string,
compiledCatalog: string,
namespace?: CompiledCatalogNamespace
) {
let ext: string
switch (namespace) {
case "es":
ext = "mjs"
break
case "ts":
case "json":
ext = namespace
break
default:
ext = "js"
}
const filename = `${replacePlaceholders(this.path, { locale })}.${ext}`
await writeFile(filename, compiledCatalog)
return filename
}
async read(locale: string): Promise<CatalogType> {
return await this.format.read(this.getFilename(locale), locale)
}
async readAll(): Promise<AllCatalogsType> {
const res: AllCatalogsType = {}
await Promise.all(
this.locales.map(
async (locale) => (res[locale] = await this.read(locale))
)
)
// statement above will save locales in object in undetermined order
// resort here to have keys order the same as in locales definition
return this.locales.reduce<AllCatalogsType>((acc, locale: string) => {
acc[locale] = res[locale]
return acc
}, {})
}
async readTemplate(): Promise<CatalogType> {
const filename = this.templateFile
return await this.format.read(filename, undefined)
}
get sourcePaths() {
const includeGlobs = this.include.map((includePath) => {
const isDir = isDirectory(includePath)
/**
* glob library results from absolute patterns such as /foo/* are mounted onto the root setting using path.join.
* On windows, this will by default result in /foo/* matching C:\foo\bar.txt.
*/
return isDir
? normalize(
path.resolve(
process.cwd(),
includePath === "/" ? "" : includePath,
"**/*.*"
)
)
: includePath
})
const patterns =
includeGlobs.length > 1 ? `{${includeGlobs.join(",")}}` : includeGlobs[0]
return glob.sync(patterns, { ignore: this.exclude, mark: true })
}
get localeDir() {
const localePatternIndex = this.path.indexOf(LOCALE)
if (localePatternIndex === -1) {
throw Error(`Invalid catalog path: ${LOCALE} variable is missing`)
}
return this.path.substr(0, localePatternIndex)
}
get locales() {
return this.config.locales
}
}
function getTemplatePath(ext: string, path: string) {
return path.replace(LOCALE_SUFFIX_RE, "messages" + ext)
}
export const cleanObsolete = R.filter(
(message: ExtractedMessageType) => !message.obsolete
)
export function order<T extends ExtractedCatalogType>(
by: OrderBy
): (catalog: T) => T {
return {
messageId: orderByMessageId,
message: orderByMessage,
origin: orderByOrigin,
}[by]
}
/**
* Object keys are in the same order as they were created
* https://stackoverflow.com/a/31102605/1535540
*/
function orderByMessageId<T extends ExtractedCatalogType>(messages: T): T {
return Object.keys(messages)
.sort()
.reduce((acc, key) => {
;(acc as any)[key] = messages[key]
return acc
}, {} as T)
}
function orderByOrigin<T extends ExtractedCatalogType>(messages: T): T {
function getFirstOrigin(messageKey: string) {
const sortedOrigins = messages[messageKey].origin.sort((a, b) => {
if (a[0] < b[0]) return -1
if (a[0] > b[0]) return 1
return 0
})
return sortedOrigins[0]
}
return Object.keys(messages)
.sort((a, b) => {
const [aFile, aLineNumber] = getFirstOrigin(a)
const [bFile, bLineNumber] = getFirstOrigin(b)
if (aFile < bFile) return -1
if (aFile > bFile) return 1
if (aLineNumber < bLineNumber) return -1
if (aLineNumber > bLineNumber) return 1
return 0
})
.reduce((acc, key) => {
;(acc as any)[key] = messages[key]
return acc
}, {} as T)
}
export function orderByMessage<T extends ExtractedCatalogType>(messages: T): T {
// hardcoded en-US locale to have consistent sorting
// @see https://github.com/lingui/js-lingui/pull/1808
const collator = new Intl.Collator("en-US")
return Object.keys(messages)
.sort((a, b) => {
const aMsg = messages[a].message || ""
const bMsg = messages[b].message || ""
return collator.compare(aMsg, bMsg)
})
.reduce((acc, key) => {
;(acc as any)[key] = messages[key]
return acc
}, {} as T)
}