primeiro commit
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
// Package hook runs post-sync hook scripts.
|
||||
package hook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
|
||||
"s3watch/internal/syncer"
|
||||
)
|
||||
|
||||
// Runner executes a configured hook script after changes.
|
||||
type Runner struct {
|
||||
path string
|
||||
dir string
|
||||
}
|
||||
|
||||
// NewRunner creates a hook runner for an executable script path.
|
||||
func NewRunner(path string, dir string) Runner {
|
||||
return Runner{path: path, dir: dir}
|
||||
}
|
||||
|
||||
// Run executes the hook and passes change counts through environment variables.
|
||||
func (r Runner) Run(ctx context.Context, result syncer.Result) error {
|
||||
if r.path == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, r.path)
|
||||
cmd.Dir = r.dir
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Env = append(os.Environ(),
|
||||
"S3WATCH_CHANGED="+strconv.FormatBool(result.Changed()),
|
||||
"S3WATCH_DOWNLOADED="+strconv.Itoa(result.Downloaded),
|
||||
"S3WATCH_UPLOADED="+strconv.Itoa(result.Uploaded),
|
||||
"S3WATCH_UPDATED="+strconv.Itoa(result.Updated),
|
||||
"S3WATCH_DELETED="+strconv.Itoa(result.Deleted),
|
||||
"S3WATCH_UNCHANGED="+strconv.Itoa(result.Unchanged),
|
||||
)
|
||||
|
||||
if err := cmd.Run(); err != nil {
|
||||
return fmt.Errorf("executing %q: %w", r.path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package hook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"s3watch/internal/syncer"
|
||||
)
|
||||
|
||||
func TestRunnerRunPassesChangeEnvironment(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
script := filepath.Join(t.TempDir(), "hook.sh")
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s,%s,%s,%s,%s,%s' \"$S3WATCH_CHANGED\" \"$S3WATCH_DOWNLOADED\" \"$S3WATCH_UPLOADED\" \"$S3WATCH_UPDATED\" \"$S3WATCH_DELETED\" \"$S3WATCH_UNCHANGED\" > hook.out\n"), 0o755); err != nil {
|
||||
t.Fatalf("writing hook script: %v", err)
|
||||
}
|
||||
|
||||
result := syncer.Result{Downloaded: 2, Uploaded: 3, Updated: 4, Deleted: 5, Unchanged: 6}
|
||||
if err := NewRunner(script, dir).Run(context.Background(), result); err != nil {
|
||||
t.Fatalf("Run() error = %v", err)
|
||||
}
|
||||
|
||||
output, err := os.ReadFile(filepath.Join(dir, "hook.out"))
|
||||
if err != nil {
|
||||
t.Fatalf("reading hook output: %v", err)
|
||||
}
|
||||
if got, want := strings.TrimSpace(string(output)), "true,2,3,4,5,6"; got != want {
|
||||
t.Fatalf("hook output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user