feat: added better error handling.

This commit is contained in:
Andrey Parhomenko 2024-06-05 14:49:23 +05:00
parent 7c8f818b0f
commit 95c9037391
3 changed files with 22 additions and 11 deletions

View file

@ -1,15 +1,16 @@
package main package main
import "surdeus.su/core/cli/tx" import "surdeus.su/core/cli/tx"
import "fmt"
import "log" import "log"
import "os" import "os"
import "io"
//import "fmt"
func main() { func main() {
term, ok := tx.NewTerminal(os.Stdin) term, err := tx.NewTerminal(os.Stdin)
if !ok { if err != nil {
// Some not terminal handling. // Some not terminal handling.
log.Fatal("not terminal") log.Fatal("tx.NewTerminal(...): %s\n", err)
} }
term.MakeRaw() term.MakeRaw()
defer term.Restore() defer term.Restore()
@ -18,11 +19,14 @@ func main() {
if err != nil { if err != nil {
log.Fatalf("term.GetSize(...): %s\n", err) 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 { for {
key, _, err := term.ReadKey() key, _, err := term.ReadKey()
if err != nil { if err != nil {
if err == io.EOF {
break
}
log.Fatalf("term.ReadLine(...): %s\n", err) log.Fatalf("term.ReadLine(...): %s\n", err)
} }
if key == tx.KeyControlC { if key == tx.KeyControlC {

8
tx/errors.go Normal file
View file

@ -0,0 +1,8 @@
package tx
import "errors"
var (
ErrNoInputProvided = errors.New("no input provided")
ErrNotTerminal = errors.New("not terminal")
)

View file

@ -13,24 +13,23 @@ type Terminal struct {
prevState *term.State prevState *term.State
} }
func NewTerminal(input *os.File) (*Terminal, bool) { func NewTerminal(input *os.File) (*Terminal, error) {
if input == nil { if input == nil {
return nil, false return nil, ErrNoInputProvided
} }
fd := int(input.Fd()) fd := int(input.Fd())
if !term.IsTerminal(fd) { if !term.IsTerminal(fd) {
return nil, false return nil, ErrNotTerminal
} }
ret := Terminal{} ret := Terminal{}
ret.file = input ret.file = input
ret.input = bufio.NewReader(input) ret.input = bufio.NewReader(input)
ret.fd = fd ret.fd = fd
ret.x = term.NewTerminal(input, "") ret.x = term.NewTerminal(input, "")
return &ret, true return &ret, nil
} }
func (t *Terminal) MakeRaw() error { func (t *Terminal) MakeRaw() error {
@ -44,7 +43,7 @@ func (t *Terminal) MakeRaw() error {
} }
func (t *Terminal) Restore() error { func (t *Terminal) Restore() error {
if t.prevState == nil { if t == nil || t.prevState == nil {
return nil return nil
} }