forked from morethanwords/tweb
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathwatch-lang.js
More file actions
193 lines (161 loc) · 5.47 KB
/
watch-lang.js
File metadata and controls
193 lines (161 loc) · 5.47 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
const fs = require('fs');
const path = require('path');
const {spawn, execSync} = require('child_process');
const LANG_FILE_PATH = path.join(__dirname, 'src', 'lang.ts');
const LANG_SIGN_FILE_PATH = path.join(__dirname, 'src', 'langSign.ts');
const EDIT_FILE_PATH = path.join(__dirname, 'src', 'langPackLocalVersion.ts');
const npmCmd = /^win/.test(process.platform) ? 'npm.cmd' : 'npm';
// Function to read current version from App.ts
const getCurrentVersion = () => {
try {
const appContent = fs.readFileSync(EDIT_FILE_PATH, 'utf8');
const match = appContent.match(/const langPackLocalVersion = (\d+);/);
return match ? parseInt(match[1]) : 0;
} catch(error) {
console.error('❌ Error reading App.ts:', error.message);
return 0;
}
};
// Function to update version in App.ts
const updateVersion = (newVersion) => {
try {
let appContent = fs.readFileSync(EDIT_FILE_PATH, 'utf8');
appContent = `const langPackLocalVersion = ${newVersion};export default langPackLocalVersion;
`;
fs.writeFileSync(EDIT_FILE_PATH, appContent, 'utf8');
console.log(`✅ Version updated to ${newVersion}`);
execSync(`${npmCmd} run format-lang`);
} catch(error) {
console.error('❌ Error updating App.ts:', error.message);
}
};
// Function to get file hash
const getFileHash = (filePath) => {
try {
const stats = fs.statSync(filePath);
return `${stats.mtime.getTime()}_${stats.size}`;
} catch(error) {
return null;
}
};
// Function to handle file change
const handleFileChange = (filePath, fileName, lastHash, currentVersion, isUpdating) => {
if(isUpdating.value) return; // Prevent multiple updates
const currentHash = getFileHash(filePath);
if(currentHash && currentHash !== lastHash.value) {
console.log(`📝 Changes detected in ${fileName}`);
isUpdating.value = true;
currentVersion.value++;
updateVersion(currentVersion.value);
lastHash.value = currentHash;
// Reset updating flag after a delay to prevent immediate re-triggering
setTimeout(() => {
isUpdating.value = false;
}, 200);
}
};
// Function to check if files exist
const checkFilesExist = (files) => {
for(const {path, name} of files) {
if(!fs.existsSync(path)) {
console.error(`❌ File ${path} not found!`);
return false;
}
}
return true;
};
// Main watching function using fs.watch
const watchLangFile = () => {
const files = [
{path: LANG_FILE_PATH, name: 'lang.ts'},
{path: LANG_SIGN_FILE_PATH, name: 'langSign.ts'}
];
console.log('🔍 Watching for changes in lang files...');
console.log(`📁 Files: ${files.map(f => f.path).join(', ')}`);
const lastHashes = files.map(f => ({value: getFileHash(f.path)}));
const currentVersion = {value: getCurrentVersion()};
const isUpdating = {value: false};
console.log(`📊 Current version: ${currentVersion.value}`);
// Check if files exist
if(
!checkFilesExist(files.concat([{path: EDIT_FILE_PATH, name: '.env.local'}]))
) {
console.error('❌ Files not found!');
return;
}
// Create watchers for each file
const watchers = files.map((file, index) => {
return fs.watch(file.path, (eventType, filename) => {
if(eventType === 'change') {
// Small delay to complete file writing
setTimeout(() => {
handleFileChange(file.path, file.name, lastHashes[index], currentVersion, isUpdating);
}, 100);
}
});
});
// Error handling
watchers.forEach((watcher, index) => {
watcher.on('error', (error) => {
console.error(`❌ File watching error (${files[index].name}):`, error.message);
});
});
console.log('✅ Watching started. Press Ctrl+C to stop.');
// Process termination handling
const cleanup = () => {
console.log('\n🛑 Stopping watch...');
watchers.forEach(watcher => watcher.close());
process.exit(0);
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
};
// Alternative function with interval (for cases when fs.watch doesn't work)
const watchLangFileWithInterval = () => {
const files = [
{path: LANG_FILE_PATH, name: 'lang.ts'},
{path: LANG_SIGN_FILE_PATH, name: 'langSign.ts'}
];
console.log('🔍 Watching for changes in lang files (interval mode)...');
console.log(`📁 Files: ${files.map(f => f.path).join(', ')}`);
const lastHashes = files.map(f => ({value: getFileHash(f.path)}));
const currentVersion = {value: getCurrentVersion()};
console.log(`📊 Current version: ${currentVersion.value}`);
// Check if files exist
if(
!checkFilesExist(files.concat([{path: EDIT_FILE_PATH, name: '.env.local'}]))
) {
return;
}
const isUpdating = {value: false};
const interval = setInterval(() => {
files.forEach((file, index) => {
handleFileChange(file.path, file.name, lastHashes[index], currentVersion, isUpdating);
});
}, 1000);
console.log('✅ Watching started. Press Ctrl+C to stop.');
// Process termination handling
const cleanup = () => {
console.log('\n🛑 Stopping watch...');
clearInterval(interval);
process.exit(0);
};
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
};
// Start watching
if(require.main === module) {
// Try to use fs.watch, if it doesn't work - switch to interval mode
try {
watchLangFile();
} catch(error) {
console.log('⚠️ fs.watch unavailable, switching to interval mode...');
watchLangFileWithInterval();
}
}
module.exports = {
watchLangFile,
watchLangFileWithInterval,
getCurrentVersion,
updateVersion
};