File size: 11,412 Bytes
10695bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a8d2d3
 
 
10695bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a8d2d3
10695bc
 
 
 
 
 
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
import { createHash } from 'node:crypto';
import { availableParallelism } from 'node:os';
import { readFile, readdir, stat, writeFile } from 'node:fs/promises';
import { dirname, join, relative, resolve } from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { Worker } from 'node:worker_threads';
import { hasUtf8Bom } from './eu4_han_convert/src/codec.js';

const PROFILE = 'compatible';
const MANIFEST_VERSION = 1;
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const sourceRoot = join(repositoryRoot, 'localisation_source');
const encodedRoot = join(repositoryRoot, 'localisation');
const manifestPath = join(repositoryRoot, 'localisation_manifest.json');
const codecPath = join(repositoryRoot, 'tools', 'eu4_han_convert', 'src', 'codec.js');

function hash(buffer) {
  return createHash('sha256').update(buffer).digest('hex');
}

async function listLocalisationFiles(root) {
  const files = [];

  async function visit(directory) {
    const entries = await readdir(directory, { withFileTypes: true });
    for (const entry of entries) {
      const path = join(directory, entry.name);
      if (entry.isDirectory()) await visit(path);
      else if (entry.isFile() && entry.name.endsWith('.yml')) {
        files.push(relative(root, path).replaceAll('\\', '/'));
      }
    }
  }

  await visit(root);
  return files.sort();
}

async function pathExists(path) {
  try {
    await stat(path);
    return true;
  } catch (error) {
    if (error.code === 'ENOENT') return false;
    throw error;
  }
}

async function readManifest() {
  if (!await pathExists(manifestPath)) return null;
  return JSON.parse(await readFile(manifestPath, 'utf8'));
}

async function getPipeline() {
  return {
    version: MANIFEST_VERSION,
    profile: PROFILE,
    codecSha256: hash(await readFile(codecPath)),
  };
}

function isCurrentManifest(manifest, pipeline) {
  return manifest
    && manifest.version === pipeline.version
    && manifest.profile === pipeline.profile
    && manifest.codecSha256 === pipeline.codecSha256;
}

function compareFileSets(sourceFiles, encodedFiles) {
  const sourceSet = new Set(sourceFiles);
  const encodedSet = new Set(encodedFiles);
  return {
    missing: sourceFiles.filter((path) => !encodedSet.has(path)),
    extra: encodedFiles.filter((path) => !sourceSet.has(path)),
  };
}

function assertSameFileSet(sourceFiles, encodedFiles) {
  const { missing, extra } = compareFileSets(sourceFiles, encodedFiles);
  if (missing.length || extra.length) {
    throw new Error([
      ...missing.map((path) => `missing encoded file: ${path}`),
      ...extra.map((path) => `missing source file: ${path}`),
    ].join('\n'));
  }
}

async function mapConcurrent(items, concurrency, worker) {
  const results = new Array(items.length);
  let nextIndex = 0;

  async function run() {
    while (nextIndex < items.length) {
      const index = nextIndex;
      nextIndex += 1;
      results[index] = await worker(items[index]);
    }
  }

  await Promise.all(
    Array.from(
      { length: Math.min(concurrency, Math.max(items.length, 1)) },
      () => run(),
    ),
  );
  return results;
}

class CodecPool {
  constructor(size) {
    this.queue = [];
    this.nextId = 0;
    this.workers = Array.from({ length: size }, () => {
      const state = {
        worker: new Worker(new URL('./localisation_worker.mjs', import.meta.url)),
        active: null,
      };
      state.worker.on('message', (message) => {
        if (message.error) state.active.reject(new Error(message.error));
        else state.active.resolve(Buffer.from(message.output));
        state.active = null;
        this.dispatch();
      });
      state.worker.on('error', (error) => {
        if (state.active) state.active.reject(error);
        state.active = null;
        this.dispatch();
      });
      return state;
    });
  }

  run(operation, input) {
    return new Promise((resolveJob, rejectJob) => {
      this.queue.push({
        id: this.nextId,
        operation,
        input,
        resolve: resolveJob,
        reject: rejectJob,
      });
      this.nextId += 1;
      this.dispatch();
    });
  }

  dispatch() {
    for (const state of this.workers) {
      if (state.active || !this.queue.length) continue;
      state.active = this.queue.shift();
      state.worker.postMessage({
        id: state.active.id,
        operation: state.active.operation,
        input: state.active.input,
      });
    }
  }

  async close() {
    await Promise.all(this.workers.map(({ worker }) => worker.terminate()));
  }
}

async function writeManifest(pipeline, entries) {
  const manifest = {
    ...pipeline,
    files: Object.fromEntries(
      Object.entries(entries).sort(([left], [right]) => left.localeCompare(right)),
    ),
  };
  await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
}

async function build(concurrency, codecPool) {
  const sourceFiles = await listLocalisationFiles(sourceRoot);
  const encodedFiles = await listLocalisationFiles(encodedRoot);
  const { extra } = compareFileSets(sourceFiles, encodedFiles);
  if (extra.length) {
    throw new Error(extra.map((path) => `missing source file: ${path}`).join('\n'));
  }

  const encodedSet = new Set(encodedFiles);
  const pipeline = await getPipeline();
  const previous = await readManifest();
  const previousFiles = isCurrentManifest(previous, pipeline) ? previous.files : {};

  const results = await mapConcurrent(sourceFiles, concurrency, async (path) => {
    const sourceBuffer = await readFile(join(sourceRoot, path));
    const sourceSha256 = hash(sourceBuffer);
    const outputPath = join(encodedRoot, path);
    const outputBuffer = encodedSet.has(path) ? await readFile(outputPath) : null;
    const encodedSha256 = outputBuffer ? hash(outputBuffer) : null;
    const previousEntry = previousFiles[path];

    if (
      previousEntry
      && previousEntry.sourceSha256 === sourceSha256
      && previousEntry.encodedSha256 === encodedSha256
    ) {
      return { path, entry: previousEntry, rebuilt: false };
    }

    const expected = await codecPool.run('encode', sourceBuffer);
    const rebuilt = !outputBuffer || !outputBuffer.equals(expected);
    if (rebuilt) await writeFile(outputPath, expected);

    return {
      path,
      rebuilt,
      entry: {
        sourceSha256,
        encodedSha256: hash(expected),
      },
    };
  });

  await writeManifest(
    pipeline,
    Object.fromEntries(results.map(({ path, entry }) => [path, entry])),
  );
  const rebuilt = results.filter((result) => result.rebuilt).length;
  process.stdout.write(
    `Localisation build complete: ${rebuilt} rebuilt, ${sourceFiles.length - rebuilt} reused, ${concurrency} workers.\n`,
  );
}

async function check(concurrency, codecPool) {
  const sourceFiles = await listLocalisationFiles(sourceRoot);
  const encodedFiles = await listLocalisationFiles(encodedRoot);
  assertSameFileSet(sourceFiles, encodedFiles);

  const pipeline = await getPipeline();
  const manifest = await readManifest();
  const manifestCurrent = isCurrentManifest(manifest, pipeline);
  const results = await mapConcurrent(sourceFiles, concurrency, async (path) => {
    const sourceBuffer = await readFile(join(sourceRoot, path));
    const encodedBuffer = await readFile(join(encodedRoot, path));
    if (!hasUtf8Bom(encodedBuffer)) throw new Error(`missing UTF-8 BOM: ${path}`);

    const sourceSha256 = hash(sourceBuffer);
    const encodedSha256 = hash(encodedBuffer);
    const entry = manifestCurrent ? manifest.files[path] : null;
    if (
      entry
      && entry.sourceSha256 === sourceSha256
      && entry.encodedSha256 === encodedSha256
    ) {
      return false;
    }

    const expected = await codecPool.run('encode', sourceBuffer);
    if (!encodedBuffer.equals(expected)) {
      throw new Error(`encoded localisation is out of date: ${path}`);
    }
    return true;
  });

  if (!manifestCurrent || results.some(Boolean)) {
    throw new Error('localisation_manifest.json is out of date; run the build command');
  }

  process.stdout.write(
    `Localisation check complete: ${sourceFiles.length} verified, 0 re-encoded, ${concurrency} workers.\n`,
  );
}

async function source(concurrency, codecPool) {
  const encodedFiles = await listLocalisationFiles(encodedRoot);
  const sourceFiles = await listLocalisationFiles(sourceRoot);
  const { missing } = compareFileSets(sourceFiles, encodedFiles);
  if (missing.length) {
    throw new Error(missing.map((path) => `missing encoded file: ${path}`).join('\n'));
  }

  const sourceSet = new Set(sourceFiles);
  const pipeline = await getPipeline();
  const previous = await readManifest();
  const previousFiles = isCurrentManifest(previous, pipeline) ? previous.files : {};

  const results = await mapConcurrent(encodedFiles, concurrency, async (path) => {
    const encodedBuffer = await readFile(join(encodedRoot, path));
    if (!hasUtf8Bom(encodedBuffer)) throw new Error(`missing UTF-8 BOM: ${path}`);

    const encodedSha256 = hash(encodedBuffer);
    const outputPath = join(sourceRoot, path);
    const sourceBuffer = sourceSet.has(path) ? await readFile(outputPath) : null;
    const sourceSha256 = sourceBuffer ? hash(sourceBuffer) : null;
    const previousEntry = previousFiles[path];

    if (previousEntry) {
      const sourceChanged = previousEntry.sourceSha256 !== sourceSha256;
      const encodedChanged = previousEntry.encodedSha256 !== encodedSha256;
      if (sourceChanged && encodedChanged) throw new Error(`localisation conflict: ${path}`);
      if (sourceChanged) throw new Error(`readable source is newer; run the build command: ${path}`);
      if (!encodedChanged) return { path, entry: previousEntry, decoded: false };
    }

    const decodedBuffer = await codecPool.run('decode', encodedBuffer);
    await writeFile(outputPath, decodedBuffer);
    return {
      path,
      decoded: true,
      entry: {
        sourceSha256: hash(decodedBuffer),
        encodedSha256,
      },
    };
  });

  await writeManifest(
    pipeline,
    Object.fromEntries(results.map(({ path, entry }) => [path, entry])),
  );
  const decoded = results.filter((result) => result.decoded).length;
  process.stdout.write(
    `Localisation source sync complete: ${decoded} decoded, ${encodedFiles.length - decoded} reused, ${concurrency} workers.\n`,
  );
}

function parseArguments(arguments_) {
  const command = arguments_[0] ?? 'build';
  if (!['build', 'source'].includes(command)) {
    throw new TypeError(`unknown command: ${command} (use node tools/validate.mjs for checking)`);
  }

  const jobsIndex = arguments_.indexOf('--jobs');
  const defaultJobs = Math.min(Math.max(availableParallelism() - 1, 1), 8);
  const concurrency = jobsIndex === -1 ? defaultJobs : Number(arguments_[jobsIndex + 1]);
  if (!Number.isInteger(concurrency) || concurrency < 1) {
    throw new TypeError('--jobs requires a positive integer');
  }

  return { command, concurrency };
}

const { command, concurrency } = parseArguments(process.argv.slice(2));
const codecPool = new CodecPool(concurrency);

try {
  if (command === 'build') await build(concurrency, codecPool);
  else await source(concurrency, codecPool);
} catch (error) {
  process.stderr.write(`${error.message}\n`);
  process.exitCode = 1;
} finally {
  await codecPool.close();
}