6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-20 13:58:22 +00:00

Fix client.Read() context usage

This commit is contained in:
James Mills 2023-03-12 15:17:57 +10:00
parent 60abd2fae6
commit d5c9b6d825
No known key found for this signature in database
GPG Key ID: AC4C014F1440EBD6
2 changed files with 19 additions and 21 deletions

@ -1,6 +1,7 @@
package main package main
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
@ -9,7 +10,6 @@ import (
"github.com/mattn/go-isatty" "github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/net/context"
"go.salty.im/saltyim" "go.salty.im/saltyim"
) )
@ -76,32 +76,16 @@ func init() {
} }
func read(follow bool, extraenvs, prehook, posthook string, args ...string) { func read(follow bool, extraenvs, prehook, posthook string, args ...string) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel() defer cancel()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
cancel()
}()
opts := []saltyim.ReadOption{ opts := []saltyim.ReadOption{
saltyim.WithExtraEnvs(extraenvs), saltyim.WithExtraEnvs(extraenvs),
saltyim.WithPreHook(prehook), saltyim.WithPreHook(prehook),
saltyim.WithPostHook(posthook), saltyim.WithPostHook(posthook),
} }
if follow { if !follow {
for msg := range cli.Subscribe(ctx, opts...) {
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println(saltyim.FormatMessage(msg.Text))
} else {
fmt.Println(msg.Text)
}
}
} else {
msg, err := cli.Read(opts...) msg, err := cli.Read(opts...)
if err != nil { if err != nil {
if err == saltyim.ErrNoMessages { if err == saltyim.ErrNoMessages {
@ -115,5 +99,19 @@ func read(follow bool, extraenvs, prehook, posthook string, args ...string) {
} else { } else {
fmt.Println(msg.Text) fmt.Println(msg.Text)
} }
return
}
msgs := cli.Subscribe(ctx, opts...)
select {
case msg := <-msgs:
if isatty.IsTerminal(os.Stdout.Fd()) {
fmt.Println(saltyim.FormatMessage(msg.Text))
} else {
fmt.Println(msg.Text)
}
case <-ctx.Done():
close(msgs)
return
} }
} }

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1 version https://git-lfs.github.com/spec/v1
oid sha256:a41cea81148f0a7b01c94011223272c9bcbd86ea086f4338d7b6cca2258a2e38 oid sha256:11a097d990f4dfee2f727c9aac96ba1bc46bac19e1803da3114dcc786b20f0c6
size 29761883 size 30206460