From 9acae0ee0cf8d01d67f5e05909d21efe4d9d6bcb Mon Sep 17 00:00:00 2001
From: Foil-hat-guy <dev@foilhatguy.casa>
Date: Wed, 30 Apr 2025 02:02:55 +0300
Subject: [PATCH] Validate tty file name function is added.

---
 go.mod  |  5 +++++
 go.sum  |  4 ++++
 stty.go | 31 ++++++++++++++++++++++++++-----
 3 files changed, 35 insertions(+), 5 deletions(-)
 create mode 100644 go.sum

diff --git a/go.mod b/go.mod
index fbd413e..746faae 100644
--- a/go.mod
+++ b/go.mod
@@ -1,3 +1,8 @@
 module code.foilhatguy.casa/pub/stty
 
 go 1.19
+
+require (
+	golang.org/x/sys v0.15.0 // indirect
+	golang.org/x/term v0.15.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..0871f56
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,4 @@
+golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
+golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
+golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
diff --git a/stty.go b/stty.go
index 5888f7c..7fa39a9 100644
--- a/stty.go
+++ b/stty.go
@@ -2,12 +2,33 @@ package stty
 
 import (
 	"fmt"
+	"os"
+    "golang.org/x/sys/unix"
+	"golang.org/x/term"
 	"os/exec"
 )
 
 type stty struct {
 }
 
+func ValidateTtyFile(filepath string) error {
+    file, err := os.Open(filepath)
+	if err != nil {
+		return err
+	}
+	defer file.Close()
+
+	err = unix.Access(filepath, unix.W_OK)
+	if err != nil {
+		return err
+	}
+
+	if term.IsTerminal(int(file.Fd())) {
+		return nil
+	}
+	return fmt.Errorf("File is not a tty.")
+}
+
 func Get() (*stty, error) {
 	checkSttyCMD := exec.Command("stty", "--version")
 	sttyOutput, err := checkSttyCMD.Output()
@@ -37,19 +58,19 @@ func (s *stty) CheckBaudRate(portPath string) (baudrate int, err error) {
 	return baudrate, nil
 }
 
-func (s *stty) TestBaudRate(portPath string, baudrate int) (bool, error) {
+func (s *stty) TestBaudRate(portPath string, baudrate int) (error) {
 	err := s.SetBaudRate(portPath, baudrate)
 	if err != nil {
-		return false, fmt.Errorf("Failed to set baudrate using stty. Because: " + err.Error())
+		return fmt.Errorf("Failed to set baudrate using stty. Because: " + err.Error())
 	}
 
 	newBaudRate, err := s.CheckBaudRate(portPath)
 	if err != nil {
-		return false, fmt.Errorf("Failed to check baudrate using stty. Because: " + err.Error())
+		return fmt.Errorf("Failed to check baudrate using stty. Because: " + err.Error())
 	}
 
 	if newBaudRate == baudrate {
-		return true, nil
+		return nil
 	}
-	return false, nil
+	return fmt.Errorf("Selected baudrate is not supported.") 
 }