Skip to content

danielgatis/go-pty

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-pty

Go Report Card License MIT Go Doc

A simple Go library for creating and managing pseudo-terminals (PTY). It provides a clean API for spawning processes with terminal emulation.

Installation

go get github.com/danielgatis/go-pty

Usage

Basic Example

package main

import (
	"fmt"
	"io"
	"strings"

	"github.com/danielgatis/go-pty"
)

func main() {
	// Create a new PTY running a simple command
	p, err := pty.New(24, 80, &pty.ShellConfig{
		Program: "/bin/sh",
		Args:    []string{"-c", "echo hello"},
	})
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	defer p.Close()

	// Read the output
	buf := make([]byte, 1024)
	n, err := p.Read(buf)
	if err != nil && err != io.EOF {
		fmt.Printf("Error: %v\n", err)
		return
	}

	output := strings.TrimSpace(string(buf[:n]))
	fmt.Println(output) // Output: hello
}

Interactive Shell

package main

import (
	"fmt"
	"io"
	"os"
	"os/signal"
	"syscall"

	"github.com/danielgatis/go-pty"
	"golang.org/x/term"
)

func main() {
	shell := os.Getenv("SHELL")
	if shell == "" {
		shell = "/bin/sh"
	}

	// Create a new PTY
	p, err := pty.New(24, 80, &pty.ShellConfig{
		Program: shell,
		Env: map[string]string{
			"TERM": "xterm-256color",
		},
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
	defer p.Close()

	// Put the terminal in raw mode
	oldState, _ := term.MakeRaw(int(os.Stdin.Fd()))
	defer term.Restore(int(os.Stdin.Fd()), oldState)

	// Handle window resize
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGWINCH)
	go func() {
		for range sigCh {
			width, height, _ := term.GetSize(int(os.Stdout.Fd()))
			p.Resize(uint16(height), uint16(width))
		}
	}()

	// Copy stdin to PTY
	go io.Copy(p, os.Stdin)

	// Copy PTY to stdout
	io.Copy(os.Stdout, p)
}

With Custom Environment Variables

p, err := pty.New(24, 80, &pty.ShellConfig{
	Program: "/bin/sh",
	Args:    []string{"-c", "echo $MY_VAR"},
	Env: map[string]string{
		"MY_VAR": "custom_value",
	},
})

API

Types

ShellConfig

Configuration for the shell process to be spawned.

type ShellConfig struct {
	Program string            // Path to the executable to run
	Args    []string          // Command-line arguments
	Env     map[string]string // Additional environment variables
}

PTY

Represents a pseudo-terminal with an associated process. Implements io.ReadWriter.

Functions

New

func New(rows, cols uint16, shellCfg *ShellConfig) (*PTY, error)

Creates a new PTY with the specified dimensions and shell configuration.

Methods

Read

func (p *PTY) Read(b []byte) (int, error)

Reads data from the PTY. Implements io.Reader.

Write

func (p *PTY) Write(b []byte) (int, error)

Writes data to the PTY. Implements io.Writer.

Resize

func (p *PTY) Resize(rows, cols uint16) error

Changes the terminal size. Sends SIGWINCH to notify the process.

SetPixelSize

func (p *PTY) SetPixelSize(width, height uint16) error

Sets the pixel dimensions of the terminal.

Size

func (p *PTY) Size() (rows, cols uint16)

Returns the current terminal size in rows and columns.

File

func (p *PTY) File() *os.File

Returns the underlying os.File for advanced operations.

Wait

func (p *PTY) Wait() error

Waits for the process to exit and returns its exit status.

Close

func (p *PTY) Close() error

Closes the PTY and kills the associated process. Safe to call multiple times.

License

Copyright (c) 2023-present Daniel Gatis

Licensed under MIT License

About

A simple Go library for creating and managing pseudo-terminals (PTY).

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages