Skip to content

Commit

Permalink
add single file watching
Browse files Browse the repository at this point in the history
  • Loading branch information
justone committed Jun 8, 2016
1 parent ea05e90 commit d8d054f
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions watch.go
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"os"
"os/exec"
"strconv"
"time"
Expand All @@ -12,7 +13,8 @@ import (

type WatchCommand struct {
Message string `short:"m" long:"message" description:"Message to send."`
Pid int `short:"p" long:"pid" description:"Watch after PID exits."`
Pid int `short:"p" long:"pid" description:"Notify after PID exits."`
File string `short:"f" long:"file" description:"Notify after file stops changing."`
Level float64 `short:"l" long:"level" description:"Notification level (1-5), higher numbers indictate higher importance" default:"3"`
}

Expand All @@ -21,8 +23,8 @@ var watchCommand WatchCommand
func (x *WatchCommand) Execute(args []string) error {
bus := pmb.GetPMB(globalOptions.Primary)

if len(watchCommand.Message) == 0 && watchCommand.Pid == 0 {
return fmt.Errorf("A message is required")
if len(watchCommand.Message) == 0 && watchCommand.Pid == 0 && watchCommand.File == "" {
return fmt.Errorf("A message or pid or file is required")
}

// fail fast if pid isn't found
Expand All @@ -33,6 +35,11 @@ func (x *WatchCommand) Execute(args []string) error {
return fmt.Errorf("Process %d not found.", watchCommand.Pid)
}
}
if len(watchCommand.File) > 0 {
if _, err := os.Stat(watchCommand.File); os.IsNotExist(err) {
return fmt.Errorf("File %s not found.", watchCommand.File)
}
}

id := pmb.GenerateRandomID("watch")

Expand Down Expand Up @@ -79,6 +86,24 @@ func runWatch(conn *pmb.Connection, id string) error {
message = fmt.Sprintf("Command [%s] completed.", watchExecutable)
}
}
if len(watchCommand.File) > 0 {
var prevSize int64
prevSize = -1
for {
statInfo, _ := os.Stat(watchCommand.File)
if statInfo.Size() == prevSize {
logrus.Infof("File stabilized.")
break
} else {
prevSize = statInfo.Size()
time.Sleep(5 * time.Second)
}
}

if len(message) == 0 {
message = fmt.Sprintf("File [%s] stabilized.", watchCommand.File)
}
}

note := pmb.Notification{Message: message, Level: watchCommand.Level}
return pmb.SendNotification(conn, note)
Expand Down

0 comments on commit d8d054f

Please sign in to comment.