-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-msg.js
executable file
·116 lines (104 loc) · 2.54 KB
/
update-msg.js
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
#!/usr/bin/env node
const printf = require('printf');
const fs = require('fs');
const _ = require('lodash');
function escapeStr(str) {
let s = '';
for (let i = 0; i < str.length; ++i) {
let c = str.charAt(i);
switch (c.charCodeAt(0)) {
case 0x07: c = '\\a'; break;
case 0x08: c = '\\b'; break;
case 0x09: c = '\\t'; break;
case 0x0a: c = '\\n'; break;
case 0x0b: c = '\\v'; break;
case 0x0c: c = '\\f'; break;
case 0x0d: c = '\\r'; break;
case 0x22: c = '\\"'; break;
case 0x5c: c = '\\'; break;
}
s += c;
}
return s;
}
// Replaces all printf format specifiers with the string specifier ('%s')
function simplifyFmtStr(fmt) {
const f = new printf.Formatter(fmt);
let s = '';
for (let i = 0; i < f._tokens.length; ++i) { // FIXME
const t = f._tokens[i];
if (_.isString(t)) {
if (t == '%') {
s += '%%';
} else {
s += t;
}
} else {
s += '%s';
}
}
return escapeStr(s);
}
function writeHeader(fd) {
fs.writeSync(fd, `/* This file was generated by the \`update-msg\` tool. */
#include <stddef.h>
static const struct {
unsigned id;
const char* msg;
} log_messages[] = {
`);
}
function writeMsg(fd, id, msg) {
fs.writeSync(fd, ` { ${id}, "${msg}" },
`);
}
function writeFooter(fd) {
fs.writeSync(fd, `};
#ifdef __cplusplus
extern "C" {
#endif
const void* _log_message_data = log_messages;
size_t _log_message_data_size = sizeof(log_messages);
#ifdef __cplusplus
} // extern "C"
#endif
`);
}
try {
// Process arguments
const srcFile = process.argv[2];
const destFile = process.argv[3];
if (_.isUndefined(srcFile)) {
throw new Error('Source file is not specified');
}
if (_.isUndefined(destFile)) {
throw new Error('Destination file is not specified');
}
// Parse source JSON file
let msgs = JSON.parse(fs.readFileSync(srcFile).toString());
if (!_.isArray(msgs)) {
throw new Error('Invalid format of the message data');
}
_.forEach(msgs, (m) => {
if (!_.has(m, 'id') || !_.has(m, 'msg')) {
throw new Error('Invalid format of the message data');
}
// Simplify a printf format string
m.msg = simplifyFmtStr(m.msg);
});
// Sort messages by ID
msgs = _.sortBy(msgs, (m) => {
return m.id;
});
// Generate destination source file
const fd = fs.openSync(destFile, 'w');
writeHeader(fd);
_.forEach(msgs, (m) => {
writeMsg(fd, m.id, m.msg);
});
writeFooter(fd);
fs.closeSync(fd);
} catch (e) {
console.error(`Error: ${e.message}`);
process.exit(1);
}