24 Commits
v1.5 ... v1.9

Author SHA1 Message Date
dengsgo
789caba260 发行 1.9版本 2019-04-04 14:48:11 +08:00
dengsgo
86923ffdab 增加 build脚本 2019-04-04 14:44:43 +08:00
dengsgo
72807c78a9 增加 changelog 2019-04-04 14:30:54 +08:00
dengsgo
1f4d27491b 增加 readme国际化 2019-04-04 14:30:35 +08:00
dengsgo
758bd1e409 优化 path(break change) 2019-04-04 10:46:52 +08:00
dengsgo
5c31d76fac 优化 逻辑 2019-04-03 18:04:07 +08:00
dengsgo
bee37e29e6 增加 监听文件夹 2019-04-02 18:37:46 +08:00
dengsgo
5f43051ae8 增加 监听文件夹数 2019-04-01 16:44:16 +08:00
dengsgo
9004aceb91 删除 冗余代码 2019-04-01 16:20:20 +08:00
dengsgo
8d5c11d20d 优化 逻辑,时间复杂度 2019-04-01 16:18:01 +08:00
dengsgo
2eb994561d 优化 types in 2019-04-01 15:32:27 +08:00
dengsgo
c8d8cfff72 发行 1.8版本 2019-02-27 10:38:17 +08:00
dengsgo
0cd4beac62 发行 1.7版本 2019-01-24 14:11:34 +08:00
dengsgo
4e9eecd0cc 修复 某些情况下cmd异常导致进程挂掉的问题 2019-01-24 14:02:56 +08:00
dengsgo
042038a60e 修复 time 2019-01-23 10:27:26 +08:00
dengsgo
aa27fa263a 发行 1.6版本 2019-01-19 17:30:33 +08:00
dengsgo
51d5c22a7c 优化 去除无效的输出 2019-01-19 17:17:55 +08:00
dengsgo
8e99507ff4 修改 log pre 2019-01-19 17:10:07 +08:00
dengsgo
433ea136e4 增加 jason-gao 2019-01-14 14:12:33 +08:00
dengsgo
30f7a2eead 修改 默认delay 2019-01-08 15:51:02 +08:00
dengsgo
0c5cd4a468 增加 dirs规则 2019-01-08 15:49:21 +08:00
刘邓
4d0bc0886d Merge pull request #3 from jason-gao/master
fix:callback url request fail error deal
2019-01-08 13:54:55 +08:00
jason-gao
2e717bc6ec fix:callback url request fail error deal 2019-01-07 21:49:45 -08:00
dengsgo
e53bb7aadd 修改 readme 2019-01-03 11:50:36 +08:00
9 changed files with 279 additions and 126 deletions

View File

@@ -1,3 +1,42 @@
### Release v1.9
2019.04.03
- 优化 文件夹监听效率,减少大量深层文件夹遍历的时间
- 优化 代码逻辑
- 增加 readme 英文说明
- 修复 偶现监听项目主目录无效的问题
### Release v1.8
2019.02.27
- 使用 go1.12 编译
### Release v1.7
2019.01.24
- 修复 time 内存
- 修复 某些情况下cmd异常导致进程挂掉的问题
### Release v1.6
2019.01.19
- 修复 http 通知失败导致进程崩溃
- 增加 includeDirs 参数规则验证
- 修改 delayMillSecond 默认值,2000
- 增加 贡献者 @jason-gao
- 优化 log
### Release v1.5
2019.01.03

153
README.md
View File

@@ -1,8 +1,11 @@
## 项目说明
fileboy文件变更监听通知系统使用 Go 编写。
适用于 Hot Reload 典型的如开发go项目无需每次手动执行 go build又比如前端 node 打包) 或者 系统监控的场景。
___
Fileboy, File Change Monitoring Notification System, written with Go.
For Hot Reload scenarios (typically for developing go projects without having to perform go build manually every time; for example, front-end node packaging) or system monitoring.
## 特性
@@ -14,10 +17,20 @@ fileboy文件变更监听通知系统使用 Go 编写。
- 支持冗余任务丢弃,自定义冗余任务范围
- 支持 http 通知
- 更多...
___
- Minimalist usage and configuration
- Support multiple platforms, Windows/Linux/MacOS
- Supports custom file listening scope, listening for specified folders/not listening for specified folders/specified suffix files
- Support for setting up multiple commands
- Command support variable placeholders
- Supporting redundant task discarding and customizing redundant task scope
- Supporting HTTP notifications
- more...
## 编译环境
go version >=1.10推荐 1.11
go version 1.12
## 更新日志
@@ -28,15 +41,16 @@ go version >=1.10,推荐 1.11
### 下载二进制文件
Github: [正式版 v1.5](https://github.com/dengsgo/fileboy/releases)
Gitee: [正式版 v1.5](https://gitee.com/dengsgo/fileboy/releases)
Github: [download v1.9](https://github.com/dengsgo/fileboy/releases)
Gitee: [dowmload v1.9](https://gitee.com/dengsgo/fileboy/releases)
下载已经编译好的对应平台二进制文件,重命名为`fileboy`, 加入系统 Path 中即可。
___
Download the compiled binary file of the corresponding platform, rename it `fileboy', and add it to the system Path.
### 源码编译
clone 该项目,进入主目录,运行命令:
clone 该项目,进入主目录,运行命令:
```shell
## 安装依赖
go get -u gopkg.in/fsnotify/fsnotify.v1
@@ -46,22 +60,36 @@ go build
## 运行
./fileboy
```
___
Clone project, enter the project directory, run the command:
```shell
## installation dependency
go get-u gopkg.in/fsnotify/fsnotify.v1
go get-u gopkg.in/yaml.v2
## compile
go build
## run
./fileboy
```
## 使用
fileboy 的正常运行依赖于 `filegirl.yaml` 配置,所以首次在项目中使用需要初始化 `filegirl.yaml`。
- 进入你想要 hot reload 的项目主目录下;
- 运行 `fileboy init`,会在该目录下生成 `filegirl.yaml`文件;
- 查看 `filegirl.yaml`,修改为适合自己项目的配置项;
- 运行 `fileboy`即可.
如果你定义了 `command -> exec`命令,想事先确认是否能正常执行,可以运行 `fileboy exec`命令,系统会尝试运行你的自定义命令。
如果你定义了 `command -> exec`命令,想事先确认是否能正常执行,可以运行 `fileboy exec`命令,系统会尝试运行你的自定义命令。
你可以使用 `fileboy help`查看使用帮助。
___
The normal operation of fileboy depends on the `filegirl.yaml` configuration, so for the first time in a project, `filegirl.yaml` needs to be initialized.
- Enter the project home directory where you want hot reload;
- Running `fileboy init` will generate `filegirl. yaml` files in this directory.
- View `filegirl. yaml` and modify it to a configuration item suitable for your project.
- Run `fileboy`.
If you define the `command-> exec` command, you can run the `fileboy exec` command to confirm whether it can be executed properly in advance. The system will try to run your custom command.
You can use `fileboy help` to see help info.
## filegirl.yaml 配置文件说明
@@ -111,13 +139,13 @@ command:
- go version
- go env
# 文件变更后命令在xx毫秒后才会执行单位为毫秒
# 文件变更后命令在xx毫秒后才会执行单位为毫秒
# 一个变更事件(A)如果在定义的延迟时间(t)内,又有新的文件变更事件(B)那么A会取消执行。
# B及以后的事件均依次类推直到事件Z在t内没有新事件产生Z 会执行
# 合理设置延迟时间,将有效减少冗余和重复任务的执行
# 如果不需要该特性,设置为 0
delayMillSecond: 1000
delayMillSecond: 2000
# 通知器
notifier:
# 文件更改会向该 url 发送请求POST 一段 json 文本数据)
@@ -125,10 +153,73 @@ notifier:
# 请求超时 15 秒
# POST 格式:
# Content-Type: application/json;charset=UTF-8
# User-Agent: FileBoy Net Notifier v1.5
# User-Agent: FileBoy Net Notifier v1.9
# Body: {"project_folder":"/watcher-dirs","file":"test.go","changed":1546421173070433800,"ext":".go"}
# 例: http://example.com/notifier/fileboy-listener
# 不启用通知,请留空
# 不启用通知,请留空 ""
callUrl: ""
```
___
```yaml
core:
# config version code
version: 1
# monitor section
monitor:
# directories to monitor
# test1 listen for the test1 directory in the project directory
# test1/test2 listen for the test1/test2 directory in the project directory
# test1,* listen for the test1 directory in the project directory and all its subdirectories (recursion)
# .,* listen for the project directory and all its subdirectories (recursion)
includeDirs:
- .,*
# Unmonitored directories
# .idea ignore listening to .idea directory and all its subdirectories
exceptDirs:
- .idea
- .git
- .vscode
- node_modules
- vendor
# the suffix of the listener file, which changes the file to execute commands
# .go file changes suffixed with .go execute commands
# .* all file changes execute commands in the command
types:
- .go
command:
# the files monitored have commands that change to be executed
# there can be multiple commands that will be executed in turn
# in case of interactive commands, allow external access to input
# variable placeholders are supported, and the actual values are replaced when the command is run:
# {{file}} (e.g: a.txt 、test/test2/a.go)
# {{ext}} (e.g: .go)
# {{changed}} local timestamp for file updated(nanosecond,e.g 1537326690523046400)
# variable placeholders e.gcp {{file}} /root/sync -rf 、 myCommand --{{ext}} {{changed}}
exec:
- go version
- go env
# the command will not execute until XX milliseconds after the file changes
# a change event (A) cancels execution if there is a new file change event (B) within the defined delay time (t).
# B and subsequent events are analogized in turn until event Z does not produce new events within t, and Z executes.
# reasonable setting of delay time will effectively reduce redundancy and duplicate task execution.
# If this feature is not required, set to 0
delayMillSecond: 2000
notifier:
# file changes send requests to the URL (POST JSON text data)
# the timing of triggering the request is consistent with executing the command command
# timeout 15 second
# POST :
# Content-Type: application/json;charset=UTF-8
# User-Agent: FileBoy Net Notifier v1.9
# Body: {"project_folder":"/watcher-dirs","file":"test.go","changed":1546421173070433800,"ext":".go"}
# e.g: http://example.com/notifier/fileboy-listener
# no notice is enabled. Please leave it blank. ""
callUrl: ""
```
@@ -142,8 +233,15 @@ notifier:
- [x] 支持 http 通知
- [x] 支持冗余任务丢弃
- [ ] 支持 http 合并任务的通知
___
- [x] command supports variable placeholders
- [x] Supports multiple commands
- [x] Supports listening for specified folders
- [x] Supports not listening to specified folders
- [x] Supports listening for specified suffix files
- [x] Supports HTTP notifications
- [x] Supports redundant task discarding
- [ ] Notification supporting HTTP merge tasks
## QA
@@ -154,7 +252,6 @@ notifier:
#### fileboy 可以应用在那些具体的场景?
在开发中,我们很需要一款可以帮助我们自动打包编译的工具,那 fileboy 就非常适合这样的场景。比如 go 项目的热编译,让我们可以边修改代码边运行得到反馈。又比如 PHP Swoole 框架由于常驻进程的原因无法更改代码立即reload使用 fileboy 就可以辅助做到传统 PHP 开发的体验。
对于一些需要监控文件日志或者配置变动的场景, fileboy 同样适合。你可以事先编写好相应的通知报警脚本,然后定义`filegirl.yaml`中的`command`命令,交由 fileboy 自动运行监控报警。
#### 通知器在什么时候会发送 http 请求 ?
@@ -163,22 +260,16 @@ notifier:
#### idea 下更改文件,为什么会执行两次或者多次 command ?
由于 idea 系列软件特殊的文件保存策略他会自动创建一些临时文件并且在需要时多次重写文件所以有时反映在文件上就是有多次的更改所以会出现这种情况。1.5版本增加了 `delayMillSecond` 参数,可以解决这个问题。
由于 idea 系列软件特殊的文件保存策略他会自动创建一些临时文件并且在需要时多次重写文件所以有时反映在文件上就是有多次的更改所以会出现这种情况。1.5之后的版本增加了 `delayMillSecond` 参数,可以解决这个问题。
#### filegirl.yaml 里面的 command 不支持复杂的命令吗?
对于“很复杂的命令”这种说法很难去定义,比如 `echo "hello world"`并不复杂,但是对于 fileboy 来讲,目前无法解析这种命令。
fileboy 目前支持 `命令 + 参数`这种形式的 command而且 参数中不能有""符号或者有空格。如:
`go build`:支持;
`go env`:支持;
`php swoole start --daemon`:支持
`cat a.txt | grep "q" | wc -l`:不支持
对于不支持的命令,可以把它写到一个文件里,然后在 command 中执行这个文件来解决。
#### 为什么起名为 fileboy又把配置名叫做 filegirl
@@ -191,7 +282,9 @@ fileboy 目前支持 `命令 + 参数`这种形式的 command而且 参数中
> 排名不分先后
[@dengsgo](https://www.yoytang.com) <dengsgo@yoytang.com>
[@dengsgo](https://www.yoytang.com) <dengsgo@gmail.com>
[@itwesley](https://github.com/itwesley) <wcshen1126@gmail.com>
[@jason-gao](https://github.com/jason-gao) <3048789891@qq.com>

View File

@@ -9,11 +9,16 @@ import (
"math/rand"
"os"
"path"
"strconv"
"strings"
"time"
)
const (
Version = 1
PreError = "ERROR:"
PreWarn = "Warn:"
)
var (
@@ -36,14 +41,24 @@ func parseConfig() {
cfg = new(FileGirl)
fc, err := ioutil.ReadFile(projectFolder + "/filegirl.yaml")
if err != nil {
log.Panicln("read filegirl.yaml file err: ", err)
log.Println(PreError, "the filegirl.yaml file in", projectFolder, "is not exist! ", err)
fmt.Print(firstRunHelp)
log.Fatalln("fileboy unable to run.")
}
err = yaml.Unmarshal(fc, cfg)
if err != nil {
log.Panicln("parsed filegirl.yaml failed: ", err)
log.Panicln(PreError, "parsed filegirl.yaml failed: ", err)
}
if cfg.Core.Version > Version {
log.Panicln("current fileboy support max version : ", Version)
log.Panicln(PreError, "current fileboy support max version : ", Version)
}
// init map
cfg.Monitor.TypesMap = map[string]bool{}
cfg.Monitor.IncludeDirsMap = map[string]bool{}
cfg.Monitor.ExceptDirsMap = map[string]bool{}
// convert to map
for _, v := range cfg.Monitor.Types {
cfg.Monitor.TypesMap[v] = true
}
log.Println(cfg)
}
@@ -51,9 +66,8 @@ func parseConfig() {
func eventDispatcher(event fsnotify.Event) {
ext := path.Ext(event.Name)
if len(cfg.Monitor.Types) > 0 &&
cfg.Monitor.Types[0] != ".*" &&
!inStringArray(ext, cfg.Monitor.Types) {
//log.Println(ext, cfg.Monitor.Types, inStringArray(ext, cfg.Monitor.Types))
!keyInMonitorTypesMap(".*", cfg) &&
!keyInMonitorTypesMap(ext, cfg) {
return
}
switch event.Op {
@@ -73,63 +87,72 @@ func eventDispatcher(event fsnotify.Event) {
func addWatcher() {
log.Println("collecting directory information...")
dirs := make([]string, 0)
for i := 0; i < len(cfg.Monitor.IncludeDirs); i++ {
darr := dirParse2Array(cfg.Monitor.IncludeDirs[i])
dirsMap := map[string]bool{
projectFolder: true,
}
for _, dir := range cfg.Monitor.IncludeDirs {
darr := dirParse2Array(dir)
if len(darr) < 1 || len(darr) > 2 {
log.Fatalln("filegirl section monitor dirs is error. ", cfg.Monitor.IncludeDirs[i])
log.Fatalln(PreError, "filegirl section monitor dirs is error. ", dir)
}
if strings.HasPrefix(darr[0], "/") {
log.Fatalln(PreError, "dirs must be relative paths ! err path:", dir)
}
if darr[0] == "." {
if len(darr) == 2 && darr[1] == "*" {
dirs = make([]string, 0)
dirs = append(dirs, ".")
// The highest priority
dirsMap = map[string]bool{
projectFolder: true,
}
listFile(projectFolder, func(d string) {
dirs = arrayUniqueAdd(dirs, d)
dirsMap[d] = true
})
break
} else {
dirs = arrayUniqueAdd(dirs, projectFolder)
dirsMap[projectFolder] = true
}
break
} else {
md := projectFolder + "/" + darr[0]
dirsMap[md] = true
if len(darr) == 2 && darr[1] == "*" {
dirs = arrayUniqueAdd(dirs, md)
listFile(md, func(d string) {
dirs = arrayUniqueAdd(dirs, d)
dirsMap[d] = true
})
} else {
dirs = arrayUniqueAdd(dirs, md)
}
}
}
for i := 0; i < len(cfg.Monitor.ExceptDirs); i++ {
p := projectFolder + "/" + cfg.Monitor.ExceptDirs[i]
dirs = arrayRemoveElement(dirs, p)
for _, dir := range cfg.Monitor.ExceptDirs {
if dir == "." {
log.Fatalln(PreError, "exceptDirs must is not project root path ! err path:", dir)
}
p := projectFolder + "/" + dir
delete(dirsMap, p)
listFile(p, func(d string) {
dirs = arrayRemoveElement(dirs, d)
delete(dirsMap, d)
})
}
for _, dir := range dirs {
for dir := range dirsMap {
log.Println("watcher add -> ", dir)
err := watcher.Add(dir)
if err != nil {
log.Fatalln(err)
}
}
log.Println("total monitored dirs: " + strconv.Itoa(len(dirsMap)))
log.Println("fileboy is ready.")
cfg.Monitor.DirsMap = dirsMap
}
func initWatcher() {
parseConfig()
var err error
if watcher != nil {
_ = watcher.Close()
}
watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Fatalln(err)
}
defer watcher.Close()
done := make(chan bool)
taskMan = newTaskMan(cfg.Command.DelayMillSecond, cfg.Notifier.CallUrl)
go func() {
for {
@@ -143,33 +166,29 @@ func initWatcher() {
if !ok {
return
}
log.Println("error:", err)
log.Println(PreError, err)
}
}
}()
addWatcher()
<-done
}
func parseArgs() {
l := len(os.Args)
if l == 1 {
_, err := ioutil.ReadFile(projectFolder + "/filegirl.yaml")
if err != nil {
log.Println("the filegirl.yaml file does not exist! ", err)
fmt.Print(firstRunHelp)
return
}
switch len(os.Args) {
case 1:
parseConfig()
done := make(chan bool)
initWatcher()
defer watcher.Close()
<-done
return
}
if l == 2 {
case 2:
c := os.Args[1]
switch c {
case "init":
err := ioutil.WriteFile(projectFolder+"/filegirl.yaml", []byte(exampleFileGirl), 0644)
if err != nil {
log.Println("error create filegirl.yaml config! ", err)
log.Println(PreError, "error create filegirl.yaml config! ", err)
return
}
log.Println("create filegirl.yaml ok")
@@ -184,6 +203,8 @@ func parseArgs() {
fmt.Print(helpStr)
}
return
default:
log.Fatalln("Unknown parameters, use `fileboy help` show help info.")
}
}

View File

@@ -8,6 +8,11 @@ type FileGirl struct {
Types []string `yaml:"types"`
IncludeDirs []string `yaml:"includeDirs"`
ExceptDirs []string `yaml:"exceptDirs"`
// convert to
TypesMap map[string]bool `yaml:"-"`
IncludeDirsMap map[string]bool `yaml:"-"`
ExceptDirsMap map[string]bool `yaml:"-"`
DirsMap map[string]bool `yaml:"-"`
}
Command struct {
Exec []string `yaml:"exec"`

12
mac-build-all Executable file
View File

@@ -0,0 +1,12 @@
export CGO_ENABLED=0
export GOARCH=amd64
export GOOS=darwin
go build -ldflags "-s -w" -o fileboy-darwin-amd64.bin
echo darwin ok
export GOOS=linux
go build -ldflags "-s -w" -o fileboy-linux-amd64.bin
echo linux ok
export GOOS=windows
go build -ldflags "-s -w" -o fileboy-windows-amd64.exe
echo windows ok

View File

@@ -34,7 +34,7 @@ func newNetNotifier(callUrl string) *NetNotifier {
func (n *NetNotifier) Put(cf *changedFile) {
if !n.CanPost {
log.Println("notifier call url ignore. ", n.CallUrl)
log.Println(PreWarn, "notifier call url ignore. ", n.CallUrl)
return
}
n.dispatch(&postParams{
@@ -48,7 +48,7 @@ func (n *NetNotifier) Put(cf *changedFile) {
func (n *NetNotifier) dispatch(params *postParams) {
b, err := json.Marshal(params)
if err != nil {
log.Println("error: json.Marshal n.params. ", err)
log.Println(PreError, "json.Marshal n.params. ", err)
return
}
client := &http.Client{
@@ -56,13 +56,21 @@ func (n *NetNotifier) dispatch(params *postParams) {
}
req, err := http.NewRequest("POST", n.CallUrl, bytes.NewBuffer(b))
if err != nil {
log.Println("error: http.NewRequest. ", err)
log.Println(PreError, "http.NewRequest. ", err)
return
}
req.Header.Set("Content-Type", "application/json;charset=UTF-8")
req.Header.Set("User-Agent", "FileBoy Net Notifier v1.5")
req.Header.Set("User-Agent", "FileBoy Net Notifier v1.9")
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
log.Println(PreError, "notifier call failed. err:", err)
return
}
defer func() {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
}()
if resp.StatusCode >= 300 {
// todo retry???
}

14
raw.go
View File

@@ -47,12 +47,12 @@ command:
- go version
- go env
# 文件变更后命令在xx毫秒后才会执行单位为毫秒
# 文件变更后命令在xx毫秒后才会执行单位为毫秒
# 一个变更事件(A)如果在定义的延迟时间(t)内,又有新的文件变更事件(B)那么A会取消执行。
# B及以后的事件均依次类推直到事件Z在t内没有新事件产生Z 会执行
# 合理设置延迟时间,将有效减少冗余和重复任务的执行
# 如果不需要该特性,设置为 0
delayMillSecond: 1000
delayMillSecond: 2000
# 通知器
notifier:
@@ -61,10 +61,10 @@ notifier:
# 请求超时 15 秒
# POST 格式:
# Content-Type: application/json;charset=UTF-8
# User-Agent: FileBoy Net Notifier v1.5
# User-Agent: FileBoy Net Notifier v1.9
# Body: {"project_folder":"/watcher-dirs","file":"test.go","changed":1546421173070433800,"ext":".go"}
# 例: http://example.com/notifier/fileboy-listener
# 不启用通知,请留空
# 不启用通知,请留空 ""
callUrl: ""
`
@@ -104,13 +104,13 @@ var logo = `
_____ _ | | _____ ____) ) | | | |___| |
| ___) | | | | | ___) | __ (| | | |\_____/
| | _| |_| |_____| |_____| |__) ) |___| | ___
|_| (_____)_______)_______)______/ \_____/ (___) V1.5
|_| (_____)_______)_______)______/ \_____/ (___) V1.9
`
var statement = `Dengsgo [dengsgo@gmail.com] Open Source with MIT License`
var versionDesc = `
Version fileboy: v1.5 filegirl: v` + strconv.Itoa(Version) + `
Released 2019.1.3
Version fileboy: v1.9 filegirl: v` + strconv.Itoa(Version) + `
Released 2019.4.3
Licence MIT
Author dengsgo [dengsgo@gmail.com]
Website https://github.com/dengsgo/fileboy

View File

@@ -36,7 +36,7 @@ func (t *TaskMan) Put(cf *changedFile) {
defer t.putLock.Unlock()
t.lastTaskId = cf.Changed
go func() {
<-time.Tick(time.Millisecond * time.Duration(t.delay))
<-time.After(time.Millisecond * time.Duration(t.delay))
if t.lastTaskId > cf.Changed {
return
}
@@ -45,12 +45,11 @@ func (t *TaskMan) Put(cf *changedFile) {
}
func (t *TaskMan) preRun(cf *changedFile) {
if t.cmd != nil && t.cmd.Process != nil {
err := t.cmd.Process.Kill()
if err != nil {
log.Println("err: ", err)
}
if t.cmd != nil && t.cmd.Process != nil && t.cmd.ProcessState != nil && !t.cmd.ProcessState.Exited() {
log.Println("stop old process ")
if err := t.cmd.Process.Kill(); err != nil {
log.Println(PreWarn, "stopped err, reason:", err)
}
}
go t.run(cf)
}
@@ -71,12 +70,12 @@ func (t *TaskMan) run(cf *changedFile) {
t.cmd.Env = os.Environ()
stdout, err := t.cmd.StdoutPipe()
if err != nil {
log.Println("error=>", err.Error())
log.Println(PreError, err.Error())
return
}
err = t.cmd.Start()
if err != nil {
log.Println("run command", carr, "error. ", err)
log.Println(PreError, "run command", carr, "error. ", err)
}
reader := bufio.NewReader(stdout)
for {
@@ -88,12 +87,12 @@ func (t *TaskMan) run(cf *changedFile) {
}
err = t.cmd.Wait()
if err != nil {
log.Println("cmd wait err ", err)
log.Println(PreWarn, "cmd wait err ", err)
break
}
if t.cmd.Process != nil {
if t.cmd.Process != nil && t.cmd.ProcessState != nil && !t.cmd.ProcessState.Exited() {
if err = t.cmd.Process.Kill(); err != nil {
log.Println("cmd cannot kill ", err)
log.Println(PreWarn, "cmd cannot kill, reason:", err)
}
}
}

40
util.go
View File

@@ -6,13 +6,9 @@ import (
"strings"
)
func inStringArray(value string, arr []string) bool {
for _, v := range arr {
if value == v {
return true
}
}
return false
func keyInMonitorTypesMap(k string, cfg *FileGirl) bool {
_, ok := cfg.Monitor.TypesMap[k]
return ok
}
func cmdParse2Array(s string, cf *changedFile) []string {
@@ -58,30 +54,10 @@ func listFile(folder string, fun func(string)) {
}
}
func arrayUniqueAdd(a []string, add string) []string {
if inStringArray(add, a) {
return a
}
return append(a, add)
}
func arrayRemoveElement(a []string, r string) []string {
i := -1
for k, v := range a {
if v == r {
i = k
break
}
}
if i == -1 {
return a
}
if len(a) == 1 && i == 0 {
return []string{}
}
return append(a[:i], a[i+1:]...)
}
func relativePath(folder, p string) string {
return strings.TrimPrefix(p, folder)
s := strings.ReplaceAll(strings.TrimPrefix(p, folder), "\\", "/")
if strings.HasPrefix(s, "/") && len(s) > 1 {
s = s[1:]
}
return s
}