1 Star 0 Fork 0

ronow2cn/xy-hserver

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
proto.js 9.20 KB
一键复制 编辑 原始数据 按行查看 历史
ronow2cn 提交于 2023-04-19 10:31 . update.by.bc
#!/usr/bin/env node
var execSync = require('child_process').execSync;
var fs = require('fs');
// ============================================================================
// go server path
var DIR_SVRGO = "svrgo"
// proto file path
var DIR_PROTO = `${DIR_SVRGO}/internal/proto/`;
// go file import prefix
var GO_IMPORT_PREFIX = "svr/"
var T = {
// "c_s" : {
// files : [],
// structs : [{key : "c", msgid : 1, tp : xxx}, ...],
// }
};
// ============================================================================
function file_exists(fn) {
return fs.existsSync(fn)
}
function read_file(fn) {
return fs.readFileSync(fn, 'utf-8');
}
function save_file(fn, text) {
fs.writeFileSync(fn, text);
}
// ============================================================================
var print_arr = [];
function print_start() {
print_arr = [];
}
function printf(indent, fmt) {
let str = "";
if (indent) {
for (i = 0; i < indent * 4; i++) {
str += " ";
}
}
str += fmt ? fmt : "";
print_arr.push(str);
}
function print_end() {
return print_arr.join("\n");
}
// ============================================================================
function print_msg_interface() {
printf(0, "package msg")
printf()
printf(0, "type Message interface {")
printf(0, " MsgId() uint32")
printf(0, " Marshal() ([]byte, error)")
printf(0, " Unmarshal([]byte) error")
printf(0, "}")
printf()
printf(0, "func Marshal(m Message) ([]byte, error) {")
printf(0, " return m.Marshal()")
printf(0, "}")
printf()
printf(0, "func Unmarshal(b []byte, m Message) error {")
printf(0, " return m.Unmarshal(b)")
printf(0, "}")
printf()
}
function print_msg_idstruct_creator(cnn_arr) {
printf(0, "var MsgCreators = map[uint32]func() Message{")
cnn_arr.forEach(cnn => {
let prefix = cnn[0];
T[prefix].structs.forEach(struct => {
printf(1, `${struct.msgid}: func() Message {`);
printf(1, ` return &${struct.tp}{}`);
printf(1, "},")
});
});
printf(0, "}");
printf();
}
function print_msg_idstruct_msgid(cnn_arr) {
cnn_arr.forEach(cnn => {
let prefix = cnn[0];
T[prefix].structs.forEach(struct => {
printf(0, `func (self *${struct.tp}) MsgId() uint32 {`)
printf(0, ` return ${struct.msgid}`)
printf(0, "}")
printf()
});
});
}
// ============================================================================
function print_msg_handler() {
printf(0, "package msg")
printf()
printf(0, "var MsgHandlers = map[uint32]func(message Message, ctx interface{}){}")
printf()
printf(0, "func Handler(msgid uint32, h func(message Message, ctx interface{})) {")
printf(0, " MsgHandlers[msgid] = h")
printf(0, "}")
printf()
}
function print_handler_init(svr, cnn_arr) {
let imports = [];
cnn_arr.forEach(cnn => {
let prefix = cnn[0];
let key = cnn[1];
if (key != "") {
imports.push(`${GO_IMPORT_PREFIX}${svr}/handler/${prefix}`);
}
});
imports.push(`${GO_IMPORT_PREFIX}${svr}/msg`);
imports.sort();
printf(0, "package handler");
printf();
printf(0, "import (");
imports.forEach(v => {
printf(0, ` "${v}"`);
});
printf(0, ")")
printf()
printf(0, "func Init() {")
cnn_arr.forEach(cnn => {
let prefix = cnn[0];
let key = cnn[1].toLocaleLowerCase();
T[prefix].structs.forEach(struct => {
if (struct.key == key) {
printf(1, `msg.Handler(${struct.msgid}, ${prefix}.${struct.tp})`)
}
});
});
printf(0, "}")
printf()
}
function print_handler(svr, prefix, tp) {
printf(0, `package ${prefix}`)
printf()
printf(0, "import (")
printf(0, ` "${GO_IMPORT_PREFIX}${svr}/msg"`)
printf(0, ")")
printf()
printf(0, `func ${tp}(message msg.Message, ctx interface{}) {`)
printf(0, ` req := message.(*msg.${tp})`)
printf(0, " req = req")
printf(0, "}")
printf()
}
// ============================================================================
function prepare() {
var filenames = fs.readdirSync(DIR_PROTO);
filenames.sort().forEach(fn => {
if (!fn.match(".proto")) {
return
}
let prefix = fn.match(/(\w+_\w+)\./)[1];
if (!T[prefix]) {
T[prefix] = {
files: [],
structs: [],
}
}
// add files
fn = DIR_PROTO + fn
T[prefix].files.push(fn);
// add struct
let text = read_file(fn);
let ele;
let i = 0;
let reg = /message\s+([\w_]+)\s*{\s*\/\/\s*msgid:\s*(\d+)/g;
let tp_msgid = [];
while (ele = reg.exec(text)) {
tp_msgid[i] = [ele[1], ele[2]];
i++
}
tp_msgid.forEach(v => {
let tp = v[0];
let msgid = v[1];
let keys = tp.match(/^([A-Za-z0-9]+)_/);
if (!keys) {
return
}
key = keys[1].toLocaleLowerCase()
T[prefix].structs.push({
key: key,
msgid: msgid,
tp: tp,
})
})
});
}
function gen_msg_files(svr, cnn_arr) {
let outdir = `${DIR_SVRGO}/${svr}/msg`;
execSync(`rm -rf ${outdir}`);
execSync(`mkdir -p ${outdir}`);
let files = [];
cnn_arr.forEach(cnn => {
let prefix = cnn[0];
T[prefix].files.forEach(v => {
files.push(v);
})
})
let dir = execSync(`cd ${DIR_SVRGO} && go list -f={{.Dir}} -m github.com/gogo/protobuf && cd ..`).toString().trim();
if (file_exists(dir)) {
execSync(`protoc -I=${dir}/gogoproto/ -I=${dir}/protobuf/ -I=${DIR_PROTO} --gogofaster_out=${outdir} ${files.join(" ")}`);
}
}
function gen_msg_handler(svr, cnn_arr) {
//handler dt
print_start();
print_msg_handler();
let text = print_end();
//save
save_file(`${DIR_SVRGO}/${svr}/msg/handler.go`, text);
}
function gen_msg_idstruct(svr, cnn_arr) {
print_start();
printf(0, "package msg");
printf();
print_msg_idstruct_creator(cnn_arr);
print_msg_idstruct_msgid(cnn_arr);
let text = print_end();
save_file(`${DIR_SVRGO}/${svr}/msg/idstruct.go`, text);
}
function gen_msg_interface(svr, cnn_arr) {
print_start()
print_msg_interface()
let text = print_end()
save_file(`${DIR_SVRGO}/${svr}/msg/message.go`, text)
}
function gen_handler_init(svr, cnn_arr) {
//handler map
print_start();
print_handler_init(svr, cnn_arr);
text = print_end();
execSync(`mkdir -p ${DIR_SVRGO}/${svr}/handler`, svr);
save_file(`${DIR_SVRGO}/${svr}/handler/init.go`, text);
}
function gen_handlers(svr, cnn_arr) {
cnn_arr.forEach(cnn => {
let prefix = cnn[0];
let key = cnn[1];
T[prefix].structs.forEach(struct => {
if (struct.key == key) {
outfile = `${DIR_SVRGO}/${svr}/handler/${prefix}/${struct.tp}.go`;
if (!file_exists(outfile)) {
print_start();
print_handler(svr, prefix, struct.tp);
text = print_end();
save_file(outfile, text);
}
}
});
});
}
// ============================================================================
function gen_proto(svr, cnn_arr) {
console.log("generation proto for ", svr);
// msg dir
gen_msg_files(svr, cnn_arr)
gen_msg_idstruct(svr, cnn_arr)
gen_msg_interface(svr, cnn_arr)
gen_msg_handler(svr, cnn_arr)
// handler dir
gen_handler_init(svr, cnn_arr)
gen_handlers(svr, cnn_arr)
}
// ============================================================================
// main
// ============================================================================
(async () => {
prepare();
print_start()
gen_proto("gate", [
["c_gw", "c"],
["gw_gs", "gs"],
])
gen_proto("game", [
["gw_gs", "gw"],
["c_gs", "c"],
["gs_rt", "rt"],
["gs_gs", "gs"],
])
gen_proto("router", [
["gs_rt", "gs"],
])
// gen_proto("bot", [
// ["c_gw", "gw"],
// ["c_gs", "gs"],
// ])
// ============================================================================
// FOR bot: keep handler files that are only needed
// ============================================================================
// execSync(`
// find ${DIR_SVRGO}/bot/handler/ -type f | \
// grep -v 'init.go' | \
// grep -v 'utils.go' | \
// grep -v '/GW_*' | \
// grep -v 'GS_UserInfo*' | \
// grep -v 'GS_LoginError*' | \
// xargs rm -f
// `)
// execSync(`
// sed -n -i '' \
// -e '1,/{/p' \
// -e '/}/,$p' \
// -e '/GW_/p' \
// -e '/GS_UserInfo/p' \
// -e '/GS_LoginError/p' \
// \
// \
// ${DIR_SVRGO}/bot/handler/init.go
// `)
})().catch(e => {
console.error(typeof e == 'string' ? e : e.message);
process.exit(1);
});
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ronow2cn/xy-hserver.git
git@gitee.com:ronow2cn/xy-hserver.git
ronow2cn
xy-hserver
xy-hserver
master

搜索帮助