Last active
December 5, 2018 20:12
-
-
Save oshvartz/c4e56fc4118ec6c83148b695cc277bbd to your computer and use it in GitHub Desktop.
fileWatcherActionExecuter in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"flag" | |
"fmt" | |
"os/exec" | |
"regexp" | |
"github.com/hpcloud/tail" | |
) | |
type PowerShell struct { | |
powerShell string | |
} | |
func New() *PowerShell { | |
ps, _ := exec.LookPath("powershell.exe") | |
return &PowerShell{ | |
powerShell: ps, | |
} | |
} | |
func (p *PowerShell) Execute(args ...string) (stdOut string, stdErr string, err error) { | |
args = append([]string{"-NoProfile", "-NonInteractive"}, args...) | |
cmd := exec.Command(p.powerShell, args...) | |
var stdout bytes.Buffer | |
var stderr bytes.Buffer | |
cmd.Stdout = &stdout | |
cmd.Stderr = &stderr | |
err = cmd.Run() | |
stdOut, stdErr = stdout.String(), stderr.String() | |
return | |
} | |
func main() { | |
filePtr := flag.String("file", "", "the file name") | |
matchPtr := flag.String("match", "", "pattern match") | |
cmdPtr := flag.String("cmd", "", "command to execute") | |
flag.Parse() | |
t, err := tail.TailFile(*filePtr, tail.Config{ | |
Follow: true, | |
ReOpen: true, | |
Poll: true, | |
}) | |
for line := range t.Lines { | |
if line.Time.Second()%10 == 0 { | |
fmt.Println("line:" + line.Text) | |
} | |
match, _ := regexp.MatchString(*matchPtr, line.Text) | |
if match { | |
fmt.Println("running:" + *cmdPtr) | |
posh := New() | |
stdout, stderr, err := posh.Execute(*cmdPtr) | |
fmt.Println(stdout) | |
fmt.Println(stderr) | |
if err != nil { | |
fmt.Println(err) | |
} | |
return | |
} | |
} | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment