Skip to content

Commit

Permalink
Add File interface instead of using os.File
Browse files Browse the repository at this point in the history
Signed-off-by: Ulysses Souza <ulyssessouza@gmail.com>
  • Loading branch information
ulyssessouza committed Dec 3, 2019
1 parent 4b1ac2b commit f652dc3
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 13 deletions.
19 changes: 11 additions & 8 deletions console.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,17 @@ import (

var ErrNotAConsole = errors.New("provided file is not a console")

type File interface {
io.ReadWriteCloser

// Fd returns its file descriptor
Fd() uintptr
// Name returns its file name
Name() string
}

type Console interface {
io.Reader
io.Writer
io.Closer
File

// Resize resizes the console to the provided window size
Resize(WinSize) error
Expand All @@ -42,10 +49,6 @@ type Console interface {
Reset() error
// Size returns the window size of the console
Size() (WinSize, error)
// Fd returns the console's file descriptor
Fd() uintptr
// Name returns the console's file name
Name() string
}

// WinSize specifies the window size of the console
Expand All @@ -70,7 +73,7 @@ func Current() Console {
}

// ConsoleFromFile returns a console using the provided file
func ConsoleFromFile(f *os.File) (Console, error) {
func ConsoleFromFile(f File) (Console, error) {
if err := checkConsole(f); err != nil {
return nil, err
}
Expand Down
6 changes: 3 additions & 3 deletions console_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func NewPty() (Console, string, error) {
}

type master struct {
f *os.File
f File
original *unix.Termios
}

Expand Down Expand Up @@ -122,15 +122,15 @@ func (m *master) Name() string {
}

// checkConsole checks if the provided file is a console
func checkConsole(f *os.File) error {
func checkConsole(f File) error {
var termios unix.Termios
if tcget(f.Fd(), &termios) != nil {
return ErrNotAConsole
}
return nil
}

func newMaster(f *os.File) (Console, error) {
func newMaster(f File) (Console, error) {
m := &master{
f: f,
}
Expand Down
4 changes: 2 additions & 2 deletions console_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,15 +198,15 @@ func makeInputRaw(fd windows.Handle, mode uint32) error {
return nil
}

func checkConsole(f *os.File) error {
func checkConsole(f File) error {
var mode uint32
if err := windows.GetConsoleMode(windows.Handle(f.Fd()), &mode); err != nil {
return err
}
return nil
}

func newMaster(f *os.File) (Console, error) {
func newMaster(f File) (Console, error) {
if f != os.Stdin && f != os.Stdout && f != os.Stderr {
return nil, errors.New("creating a console from a file is not supported on windows")
}
Expand Down

0 comments on commit f652dc3

Please sign in to comment.