package cmd
import (
"fmt"
"io"
"os"
"runtime"
"github.com/spf13/cobra"
"mercemay.top/httptap/internal/filter"
)
func newDoctorCmd() *cobra.Command {
return &cobra.Command{
Use: "doctor",
Short: "Print diagnostic information about the environment",
RunE: func(c *cobra.Command, args []string) error {
return doctor(os.Stdout)
},
}
}
// doctor runs a handful of non-destructive probes and prints results to
// w. Each check is a separate function for easy table-driven testing.
func doctor(w io.Writer) error {
for _, chk := range []func() (string, bool){
checkSocket,
checkHomeTTY,
checkFilterFields,
checkGo,
} {
msg, ok := chk()
prefix := " OK "
if !ok {
prefix = "WARN"
}
fmt.Fprintf(w, "[%s] %s\n", prefix, msg)
}
return nil
}
func checkSocket() (string, bool) {
if _, err := os.Stat(globalOpts.SocketPath); err != nil {
return fmt.Sprintf("socket %s: %v", globalOpts.SocketPath, err), false
}
return fmt.Sprintf("socket exists at %s", globalOpts.SocketPath), true
}
func checkHomeTTY() (string, bool) {
if home, _ := os.UserHomeDir(); home == "" {
return "$HOME is not set", false
}
if !isatty(os.Stdout) {
return "stdout is not a TTY; the TUI will not render", false
}
return "stdout is a TTY", true
}
func checkFilterFields() (string, bool) {
if _, err := filter.Compile("method=GET"); err != nil {
return fmt.Sprintf("filter compile: %v", err), false
}
return fmt.Sprintf("filter grammar: %d known fields", len(filter.KnownFields)), true
}
func checkGo() (string, bool) {
return fmt.Sprintf("Go runtime %s on %s/%s",
runtime.Version(), runtime.GOOS, runtime.GOARCH), true
}
// isatty is a POSIX-only shortcut; on Windows we always return false
// because we expect a Unix-y environment anyway.
func isatty(f *os.File) bool {
fi, err := f.Stat()
if err != nil {
return false
}
return (fi.Mode() & os.ModeCharDevice) != 0
}