-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathwebpack.zotero-locale-plugin.js
More file actions
216 lines (185 loc) · 5.77 KB
/
webpack.zotero-locale-plugin.js
File metadata and controls
216 lines (185 loc) · 5.77 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
let https = require('https');
let fs = require('fs');
let path = require('path');
const OUTPUT_PATH = path.resolve(__dirname, './locales');
const SIGNATURE_PATH = path.join(OUTPUT_PATH, '.signature');
// Shared preparation state across all compiler instances in a single webpack process
let localePrep = {
key: null,
promise: null
};
class ZoteroLocalePlugin {
constructor(options) {
this.locales = options.locales;
this.commitHash = options.commitHash;
// Normalize files to { src, dest } where src is repo-relative with a {locale} placeholder
// Plain strings like 'reader.ftl' expand to 'chrome/locale/{locale}/zotero/reader.ftl'
this.files = options.files.map((file) => {
if (typeof file === 'string') {
return { src: `chrome/locale/{locale}/zotero/${file}`, dest: file };
}
return file;
});
}
getRemoteURL() {
return `https://raw.githubusercontent.com/zotero/zotero/${this.commitHash}`;
}
getPrepKey() {
return JSON.stringify({
commitHash: this.commitHash,
locales: this.locales,
files: this.files
});
}
async ensureLocaleFilesReady() {
let key = this.getPrepKey();
if (localePrep.key !== key) {
localePrep = { key, promise: null };
}
if (!localePrep.promise) {
localePrep.promise = (async () => {
console.log('ZoteroLocalePlugin is running...');
await this.processFiles();
})().catch((err) => {
localePrep.promise = null;
throw err;
});
}
await localePrep.promise;
}
async downloadFile(url, outputPath) {
return new Promise((resolve, reject) => {
let settled = false;
let file = fs.createWriteStream(outputPath);
let fail = (error) => {
if (settled) {
return;
}
settled = true;
file.destroy();
fs.unlink(outputPath, () => reject(error));
};
let request = https.get(url, (response) => {
if (response.statusCode !== 200) {
response.resume();
fail(new Error(`Failed to download file (${response.statusCode}): ${url}`));
return;
}
response.pipe(file);
});
request.on('error', (err) => {
fail(new Error(`Failed to download file from ${url}: ${err.message}`));
});
file.on('finish', () => {
file.close((err) => {
if (settled) {
return;
}
if (err) {
fail(new Error(`Failed to finalize downloaded file ${outputPath}: ${err.message}`));
return;
}
settled = true;
resolve();
});
});
file.on('error', (err) => {
fail(new Error(`Failed to write downloaded file ${outputPath}: ${err.message}`));
});
});
}
getRepoRoot() {
let parentDir = path.resolve(__dirname, '..');
if (fs.existsSync(path.join(parentDir, 'chrome', 'locale'))) {
return parentDir;
}
return null;
}
async copyLocalFiles(repoRoot) {
// Remove and recreate the output directory
if (fs.existsSync(OUTPUT_PATH)) {
fs.rmSync(OUTPUT_PATH, { recursive: true, force: true });
}
fs.mkdirSync(OUTPUT_PATH, { recursive: true });
for (let locale of this.locales) {
let localeDir = path.join(OUTPUT_PATH, locale);
fs.mkdirSync(localeDir, { recursive: true });
for (let { src, dest } of this.files) {
let srcPath = path.join(repoRoot, src.replace('{locale}', locale));
let destPath = path.join(localeDir, dest);
if (!fs.existsSync(srcPath)) {
throw new Error(`Missing locale source file: ${srcPath}`);
}
fs.copyFileSync(srcPath, destPath);
}
}
}
// Downloads locale files if the commit hash has changed.
async processFiles() {
// If inside zotero-client, copy from the local tree
let repoRoot = this.getRepoRoot();
if (repoRoot) {
console.log(`Copying locale files from ${repoRoot}`);
await this.copyLocalFiles(repoRoot);
return;
}
// Load the previous commit hash from the plain text .signature file
let lastCommitHash = null;
try {
if (fs.existsSync(SIGNATURE_PATH)) {
lastCommitHash = fs.readFileSync(SIGNATURE_PATH, 'utf8').trim(); // Read as plain text
}
}
catch (err) {
console.error('Error reading .signature file:', err);
}
// If the commit hash has changed
if (lastCommitHash !== this.commitHash) {
console.log(`Detected commit hash change (was: ${lastCommitHash}, now: ${this.commitHash}). Clearing and downloading locale files...`);
// Remove and recreate the output directory
try {
if (fs.existsSync(OUTPUT_PATH)) {
fs.rmSync(OUTPUT_PATH, { recursive: true, force: true });
console.log(`Deleted existing locale directory: ${OUTPUT_PATH}`);
}
fs.mkdirSync(OUTPUT_PATH, { recursive: true });
console.log(`Recreated locale directory: ${OUTPUT_PATH}`);
}
catch (err) {
console.error('Error while resetting locale directory:', err);
return;
}
let remoteBase = this.getRemoteURL();
for (let locale of this.locales) {
let localeDir = path.join(OUTPUT_PATH, locale);
fs.mkdirSync(localeDir, { recursive: true });
for (let { src, dest } of this.files) {
let url = `${remoteBase}/${src.replace('{locale}', locale)}`;
let outputFile = path.join(localeDir, dest);
console.log(`Downloading ${url} -> ${outputFile}`);
await this.downloadFile(url, outputFile);
}
}
// Save the new commit hash in the .signature file as plain text
try {
fs.writeFileSync(SIGNATURE_PATH, this.commitHash, 'utf8');
console.log(`Updated commit hash saved to ${SIGNATURE_PATH}`);
}
catch (err) {
console.error('Error writing to .signature file:', err);
}
}
else {
console.log(`No changes detected (current hash: ${this.commitHash}). Skipping downloads.`);
}
}
apply(compiler) {
// Hook into Webpack's lifecycle
let run = async () => {
await this.ensureLocaleFilesReady();
};
compiler.hooks.beforeRun.tapPromise('ZoteroLocalePlugin', run);
compiler.hooks.watchRun.tapPromise('ZoteroLocalePlugin', run);
}
}
module.exports = ZoteroLocalePlugin;