Weather action

This commit is contained in:
nemunaire 2022-12-08 17:49:15 +01:00
commit 1def1ff67a
2 changed files with 84 additions and 8 deletions

View file

@ -4,9 +4,11 @@ import (
"bufio"
"crypto/sha512"
"errors"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
@ -19,9 +21,10 @@ type Action struct {
Description string `json:"description,omitempty"`
Path string `json:"path"`
Enabled bool `json:"enabled"`
fullPath string
}
func LoadAction(path string) (string, string, error) {
func loadAction(path string) (string, string, error) {
fd, err := os.Open(path)
if err != nil {
return "", "", err
@ -64,6 +67,45 @@ func LoadAction(path string) (string, string, error) {
return name, description, nil
}
func LoadAction(cfg *config.Config, path string) (*Action, error) {
actionsDir, err := filepath.Abs(cfg.ActionsDir)
if err != nil {
return nil, err
}
path = filepath.Join(actionsDir, path)
d, err := os.Stat(path)
if err != nil {
return nil, err
}
if !d.Mode().IsRegular() {
return nil, fmt.Errorf("%q is not a file, it cannot be an action.", path)
}
hash := sha512.Sum512([]byte(path))
// Parse content
name, description, err := loadAction(path)
if err != nil {
return nil, fmt.Errorf("Invalid action file (trying to parse %s): %s", path, err.Error())
}
if apath, err := filepath.Abs(path); err == nil {
path = apath
}
return &Action{
Id: hash[:],
Name: name,
Description: description,
Path: strings.TrimPrefix(path, actionsDir+"/"),
Enabled: d.Mode().Perm()&0111 != 0,
fullPath: path,
}, nil
}
func LoadActions(cfg *config.Config) (actions []*Action, err error) {
actionsDir, err := filepath.Abs(cfg.ActionsDir)
if err != nil {
@ -75,7 +117,7 @@ func LoadActions(cfg *config.Config) (actions []*Action, err error) {
hash := sha512.Sum512([]byte(path))
// Parse content
name, description, err := LoadAction(path)
name, description, err := loadAction(path)
if err != nil {
log.Printf("Invalid action file (trying to parse %s): %s", path, err.Error())
// Ignore invalid files
@ -96,6 +138,7 @@ func LoadActions(cfg *config.Config) (actions []*Action, err error) {
Description: description,
Path: strings.TrimPrefix(path, actionsDir+"/"),
Enabled: d.Mode().Perm()&0111 != 0,
fullPath: path,
})
}
@ -130,3 +173,9 @@ func (a *Action) Disable() error {
func (a *Action) Remove() error {
return os.Remove(a.Path)
}
func (a *Action) Launch() (cmd *exec.Cmd, err error) {
cmd = exec.Command(a.fullPath)
err = cmd.Start()
return
}