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
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 {

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
}
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
}