2020-08-06 20:58:47 +03:00
|
|
|
package tablew
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-12-18 03:51:33 +03:00
|
|
|
"errors"
|
2020-08-06 20:58:47 +03:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/neilotoole/sq/cli/output"
|
|
|
|
"github.com/neilotoole/sq/libsq/source"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewPingWriter returns a new instance. It is not safe for
|
|
|
|
// concurrent use.
|
2023-04-22 06:36:32 +03:00
|
|
|
func NewPingWriter(out io.Writer, pr *output.Printing) *PingWriter {
|
|
|
|
return &PingWriter{out: out, pr: pr}
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// PingWriter implements output.PingWriter.
|
|
|
|
type PingWriter struct {
|
|
|
|
out io.Writer
|
2023-04-22 06:36:32 +03:00
|
|
|
pr *output.Printing
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2023-04-19 08:28:09 +03:00
|
|
|
// handleLenMax is the maximum width of
|
2020-08-06 20:58:47 +03:00
|
|
|
// the sources' handles.
|
|
|
|
handleWidthMax int
|
|
|
|
}
|
|
|
|
|
2023-04-19 08:28:09 +03:00
|
|
|
// Open implements output.PingWriter.
|
2023-01-01 09:00:07 +03:00
|
|
|
func (w *PingWriter) Open(srcs []*source.Source) error {
|
2020-08-06 20:58:47 +03:00
|
|
|
for _, src := range srcs {
|
|
|
|
if len(src.Handle) > w.handleWidthMax {
|
|
|
|
w.handleWidthMax = len(src.Handle)
|
|
|
|
}
|
|
|
|
}
|
2023-01-01 09:00:07 +03:00
|
|
|
return nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
2023-04-19 08:28:09 +03:00
|
|
|
// Result implements output.PingWriter.
|
2023-01-01 09:00:07 +03:00
|
|
|
func (w *PingWriter) Result(src *source.Source, d time.Duration, err error) error {
|
2023-04-22 06:36:32 +03:00
|
|
|
w.pr.Number.Fprintf(w.out, "%-"+strconv.Itoa(w.handleWidthMax)+"s", src.Handle)
|
2023-04-26 18:16:42 +03:00
|
|
|
w.pr.Duration.Fprintf(w.out, "%10s ", d.Truncate(time.Millisecond).String())
|
2020-08-06 20:58:47 +03:00
|
|
|
|
|
|
|
// The ping result is one of:
|
|
|
|
// - success
|
|
|
|
// - timeout
|
|
|
|
// - some other error
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case err == nil:
|
2023-04-22 06:36:32 +03:00
|
|
|
w.pr.Success.Fprintf(w.out, "pong")
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2022-12-18 03:51:33 +03:00
|
|
|
case errors.Is(err, context.DeadlineExceeded):
|
2023-04-22 06:36:32 +03:00
|
|
|
w.pr.Error.Fprintf(w.out, "fail")
|
2020-08-06 20:58:47 +03:00
|
|
|
// Special rendering for timeout error
|
|
|
|
fmt.Fprint(w.out, " timeout exceeded")
|
|
|
|
|
|
|
|
default: // err other than timeout err
|
2023-04-22 06:36:32 +03:00
|
|
|
w.pr.Error.Fprintf(w.out, "fail")
|
2020-08-06 20:58:47 +03:00
|
|
|
fmt.Fprintf(w.out, " %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Fprintf(w.out, "\n")
|
2023-01-01 09:00:07 +03:00
|
|
|
return nil
|
2020-08-06 20:58:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w *PingWriter) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|