安装
# install for mac
brew install watchman
使用
使用过程分两步:
1、监听项目目录
# watchman watch-project /path/to/project
watchman watch-project /www/watch-demo
示例返回:
{
"version": "2021.12.06.00",
"watch": "/www/watch-demo",
"watcher": "fsevents"
}
2、注册触发器
2.1 编辑触发器配置内容 /www/watch-demo/watch-config.json
[
"trigger",
"/www/watch-demo",
{
"name": "watch-demo",
"expression":
[
"pcre",
"\\.go$"
],
"command":
[
"sh", "/www/watch-demo/restart.sh"
]
}
]
2.2 编辑项目自动编译重启命令shell /www/watch-demo/restart.sh
#!/bin/sh
shell_name="watch-demo.run"
#关闭旧进程
if [ `ps aux | grep ${shell_name} | grep -v grep | awk '{print $2}'` ]; then
ps aux | grep ${shell_name} | grep -v grep | awk '{print $2}' | xargs kill
fi
cd /www/watch-demo
go build -o ${shell_name} ./main.go
./${shell_name} 2>&1 &
rm -f ${shell_name}
2.3 注册触发器,内容变更自动编译重启
watchman -j < /www/watch-demo/watch-config.json
示例返回:
{
"version": "2021.12.06.00",
"triggerid": "watch-demo",
"disposition": "created"
}
可能报错:
{
"version": "2021.12.06.00",
"error": "watchman::RootResolveError: RootResolveError: unable to resolve root /www/watch-demo: RootResolveError: directory /www/watch-demo is not watched"
}
原因:未执行监听项目目录命令 watchman watch-project /www/watch-demo
解决:执行监听项目目录命令
至此,我们就添加好/www/watch-demo/
项目目录下文件变更的自动编译重启监控,每次修改内容,watchman都会自动调用我们的restart.sh命令进行处理。
查看监控运行日志
# ps aux| grep watchman 请查看--logfile关联的日志文件
tail -f /opt/homebrew/var/run/watchman/macbok-state/log
查看监控列表
watchman trigger-list /www/watch-demo
示例返回:
{
"version": "2021.12.06.00",
"triggers": [
{
"command": [
"sh",
"/www/watch-demo/restart.sh"
],
"expression": [
"pcre",
"\\.go$"
],
"name": "watch-demo"
}
]
}
删除监控
watchman trigger-del /www/watch-demo watch-demo
示例返回:
{
"version": "2021.12.06.00",
"deleted": true,
"trigger": "watch-demo"
}
更多
watchman还有更多功能,感兴趣的朋友,点击下面项目地址去挖掘一下吧~ o_O
项目地址
https://facebook.github.io/watchman/
示例代码
未经同意禁止转载!
转载请附带本文原文地址:基于watchman实现golang项目热编译自动重启,首发自 Zjmainstay学习笔记