Files
node-metaverse/tools/parseMessageTemplate.js

160 lines
4.0 KiB
JavaScript
Raw Normal View History

2017-11-24 01:00:56 +00:00
const fs = require('fs');
function getParams(str)
{
let started = false;
let lastSpace = false;
let params = '';
for(let i = 0; i < str.length; i++)
{
const c = str[i];
if (c === '{' || c === '}')
{
return params.trim();
}
else if (c === ' ' || c === '\t')
{
if (started && !lastSpace)
{
params+=' ';
lastSpace = true;
}
}
else if (c === '\n' || c === '\r')
{
//ignore
}
else
{
started = true;
lastSpace = false;
params += c;
}
}
return params.trim();
}
function getBlocks(str)
{
let started = false;
let count = 0;
let startPos = 0;
let block = [];
for(let i = 0; i < str.length; i++)
{
if (str[i] === '{')
{
if (count === 0)
{
if (!started)
{
started = true;
startPos = i;
}
}
count++
}
else if (str[i] === '}')
{
count--;
if (count === 0)
{
let s = str.substr(startPos+1, (i - startPos)-1);
block.push(s);
started = false;
}
}
}
return block;
}
fs.readFile('./msg_template.msg', (err, data) =>
{
if (err)
{
console.error(err);
}
else
{
let msgTemplate = data.toString('ascii');
//Remove all comments
const lines = msgTemplate.split('\n');
let newLines = [];
2020-11-19 16:27:29 +00:00
for (const line of lines)
{
let pos = line.indexOf('//');
if (pos !== -1)
{
line = line.substr(0, pos-1);
}
newLines.push(line);
}
msgTemplate = newLines.join('\n');
2017-11-24 01:00:56 +00:00
let messages = getBlocks(msgTemplate);
let done = false;
let msgObjects = [];
2020-11-19 16:27:29 +00:00
for (const message of messages)
2017-11-24 01:00:56 +00:00
{
let newMessage = {};
let params = getParams(message);
params = params.split(' ');
newMessage.name = params[0];
newMessage.frequency = params[1];
newMessage.id = params[2];
newMessage.flags = [];
newMessage.blocks = [];
for(let i = 3; i < params.length; i++)
{
newMessage.flags.push(params[i]);
}
let blocks = getBlocks(message);
2020-11-19 16:27:29 +00:00
for (const block of blocks)
2017-11-24 01:00:56 +00:00
{
let newBlock = {};
params = getParams(block);
params = params.split(' ');
newBlock.name = params[0];
newBlock.type = params[1];
newBlock.count = 1;
newBlock.params = [];
if (params.length>2)
{
newBlock.count = params[2]
}
let paramBlocks = getBlocks(block);
2020-11-19 16:27:29 +00:00
for (const paramBlock of paramBlocks)
2017-11-24 01:00:56 +00:00
{
let data = getParams(paramBlock);
data = data.split(' ');
let obj = {
'name': data[0],
'type': data[1],
'size': 1
};
if (data.length>2)
{
obj['size'] = data[2];
}
newBlock.params.push(obj);
2020-11-19 16:27:29 +00:00
}
2017-11-24 01:00:56 +00:00
newMessage.blocks.push(newBlock);
2020-11-19 16:27:29 +00:00
}
2017-11-24 01:00:56 +00:00
msgObjects.push(newMessage);
2020-11-19 16:27:29 +00:00
}
2017-11-24 01:00:56 +00:00
fs.writeFile('./msg_template.json', JSON.stringify(msgObjects, null, 4), (err) =>
2017-11-24 01:00:56 +00:00
{
console.log("JSON written");
});
}
});