From 95c9037391ed4444794aef8e822fc36104383f98 Mon Sep 17 00:00:00 2001 From: surdeus Date: Wed, 5 Jun 2024 14:49:23 +0500 Subject: [PATCH] feat: added better error handling. --- cmd/termsize/main.go | 14 +++++++++----- tx/errors.go | 8 ++++++++ tx/term.go | 11 +++++------ 3 files changed, 22 insertions(+), 11 deletions(-) create mode 100644 tx/errors.go diff --git a/cmd/termsize/main.go b/cmd/termsize/main.go index fac7dad..aac0c90 100644 --- a/cmd/termsize/main.go +++ b/cmd/termsize/main.go @@ -1,15 +1,16 @@ package main import "surdeus.su/core/cli/tx" -import "fmt" import "log" import "os" +import "io" +//import "fmt" func main() { - term, ok := tx.NewTerminal(os.Stdin) - if !ok { + term, err := tx.NewTerminal(os.Stdin) + if err != nil { // Some not terminal handling. - log.Fatal("not terminal") + log.Fatal("tx.NewTerminal(...): %s\n", err) } term.MakeRaw() defer term.Restore() @@ -18,11 +19,14 @@ func main() { if err != nil { log.Fatalf("term.GetSize(...): %s\n", err) } - fmt.Printf("%d\n%d\n", w, h) + term.Printf("TermSize: %dx%d\r\n", w, h) for { key, _, err := term.ReadKey() if err != nil { + if err == io.EOF { + break + } log.Fatalf("term.ReadLine(...): %s\n", err) } if key == tx.KeyControlC { diff --git a/tx/errors.go b/tx/errors.go new file mode 100644 index 0000000..53d115d --- /dev/null +++ b/tx/errors.go @@ -0,0 +1,8 @@ +package tx + +import "errors" + +var ( + ErrNoInputProvided = errors.New("no input provided") + ErrNotTerminal = errors.New("not terminal") +) diff --git a/tx/term.go b/tx/term.go index 5942d99..965d9e3 100644 --- a/tx/term.go +++ b/tx/term.go @@ -13,24 +13,23 @@ type Terminal struct { prevState *term.State } -func NewTerminal(input *os.File) (*Terminal, bool) { +func NewTerminal(input *os.File) (*Terminal, error) { if input == nil { - return nil, false + return nil, ErrNoInputProvided } fd := int(input.Fd()) if !term.IsTerminal(fd) { - return nil, false + return nil, ErrNotTerminal } - ret := Terminal{} ret.file = input ret.input = bufio.NewReader(input) ret.fd = fd ret.x = term.NewTerminal(input, "") - return &ret, true + return &ret, nil } func (t *Terminal) MakeRaw() error { @@ -44,7 +43,7 @@ func (t *Terminal) MakeRaw() error { } func (t *Terminal) Restore() error { - if t.prevState == nil { + if t == nil || t.prevState == nil { return nil }