fixing bugs, update README,Help; adding .gitignore

This commit is contained in:
Florian Walther committed 2026-10-03 16:51:55 +02:00
1 parent 847b6cd5c6
commit d5c3d03a21
4 files changed
+598 -42

No files matched your search

+268 -37
View File
@@ -6,12 +6,14 @@ import (
"io"
"os"
"os/exec"
"os/signal"
"os/user"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
"github.com/chzyer/readline"
"github.com/google/shlex"
)
// ErrNoPath is returned when 'cd' was called without a second argument.
@@ -58,11 +60,223 @@ func expandTilde(path string) string {
return path
}
// expandEnv expands environment variables in a string
// Supports $VAR, ${VAR}, and ${VAR:-default} syntax
func expandEnv(s string) string {
// Use os.ExpandEnv for simple ${VAR} and $VAR expansion
return os.ExpandEnv(s)
// splitWords splits input into words like a (very) simple POSIX shell:
// - words are separated by unquoted blanks, an unquoted # starts a comment
// - '...' is taken literally, nothing is expanded inside
// - "..." expands $VAR and ${VAR}; \ only escapes $ " \ and `
// - outside quotes \ escapes any character
// - $VAR, ${VAR} and ${VAR:-default} are expanded outside single quotes;
// an unset variable is an error, so that e.g. "rm -rf $DIR/x" never runs
// with an empty $DIR
// - ~ and ~/... are expanded at the start of an unquoted word
//
// Expanded values are never split into several words.
func splitWords(input string) ([]string, error) {
var (
words []string
b strings.Builder
inWord bool // a word has been started (even if it is still empty)
quote byte
escaped bool
)
endWord := func() {
if inWord {
words = append(words, b.String())
}
b.Reset()
inWord = false
}
for i := 0; i < len(input); i++ {
ch := input[i]
switch {
case escaped:
if quote == '"' && !strings.ContainsRune("$\"\\`", rune(ch)) {
b.WriteByte('\\')
}
b.WriteByte(ch)
inWord = true
escaped = false
case quote == '\'':
if ch == '\'' {
quote = 0
} else {
b.WriteByte(ch)
}
case ch == '\\':
escaped = true
case ch == '$':
value, n, err := expandVar(input[i:])
if err != nil {
return nil, err
}
b.WriteString(value)
// A literal "$" counts as content, an expansion that is empty does
// not (unless quoted), like in sh
if n == 1 || value != "" {
inWord = true
}
i += n - 1
case quote == '"':
if ch == '"' {
quote = 0
} else {
b.WriteByte(ch)
}
case ch == '"' || ch == '\'':
quote = ch
inWord = true
case ch == ' ' || ch == '\t' || ch == '\n':
endWord()
case ch == '#' && !inWord && b.Len() == 0:
// Comment until the end of the line
i = len(input)
case ch == '~' && !inWord && b.Len() == 0 &&
(i+1 == len(input) || strings.IndexByte("/ \t\n", input[i+1]) >= 0):
home := getHomeDir()
if home == "" {
home = "~"
}
b.WriteString(home)
inWord = true
default:
b.WriteByte(ch)
inWord = true
}
}
switch {
case escaped:
return nil, errors.New("unexpected end of input after \\")
case quote != 0:
return nil, fmt.Errorf("unterminated %c quote", quote)
}
endWord()
return words, nil
}
// expandVar expands the variable reference at the start of s (which starts
// with "$"). It returns the value and the number of bytes consumed. A "$" that
// is not followed by a variable name is returned literally.
func expandVar(s string) (string, int, error) {
if len(s) > 1 && s[1] == '{' {
end := strings.IndexByte(s, '}')
if end < 0 {
return "", 0, errors.New("missing } in variable reference")
}
name, def, hasDef := strings.Cut(s[2:end], ":-")
if !isVarName(name) {
return "", 0, fmt.Errorf("bad substitution: %s", s[:end+1])
}
value, ok := os.LookupEnv(name)
if hasDef && value == "" {
return def, end + 1, nil
}
if !ok {
return "", 0, fmt.Errorf("%s: unbound variable", name)
}
return value, end + 1, nil
}
n := 1
for n < len(s) && isVarNameByte(s[n], n == 1) {
n++
}
if n == 1 {
return "$", 1, nil
}
value, ok := os.LookupEnv(s[1:n])
if !ok {
return "", 0, fmt.Errorf("%s: unbound variable", s[1:n])
}
return value, n, nil
}
func isVarName(name string) bool {
if name == "" {
return false
}
for i := 0; i < len(name); i++ {
if !isVarNameByte(name[i], i == 0) {
return false
}
}
return true
}
func isVarNameByte(c byte, first bool) bool {
return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' ||
!first && c >= '0' && c <= '9'
}
// sanitize replaces non-printable characters (e.g. terminal escape sequences
// in directory names) with a visible escape so they cannot manipulate the
// terminal.
func sanitize(s string) string {
var b strings.Builder
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
switch {
case r == utf8.RuneError && size == 1:
fmt.Fprintf(&b, "\\x%02x", s[i])
case !unicode.IsPrint(r):
if r < 0x100 {
fmt.Fprintf(&b, "\\x%02x", r)
} else {
fmt.Fprintf(&b, "\\u%04x", r)
}
default:
b.WriteRune(r)
}
i += size
}
return b.String()
}
// isPrintable reports whether s only consists of printable characters
func isPrintable(s string) bool {
return sanitize(s) == s
}
// historyFile returns the path of the history file: $GOSH_HISTFILE if set,
// otherwise $XDG_STATE_HOME/gosh/history (default ~/.local/state/gosh/history).
// An empty string disables the history.
func historyFile() string {
if path, ok := os.LookupEnv("GOSH_HISTFILE"); ok {
return path
}
state := os.Getenv("XDG_STATE_HOME")
if state == "" {
home := getHomeDir()
if home == "" {
return ""
}
state = filepath.Join(home, ".local", "state")
}
return filepath.Join(state, "gosh", "history")
}
// prepareHistoryFile makes sure that the history file and its directory are
// only accessible by the current user. readline itself creates the file (and
// a temporary file next to it) with mode 0666 & ~umask.
func prepareHistoryFile(path string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
// Only restrict the directory if it is ours (and not e.g. $HOME itself)
if filepath.Base(dir) == "gosh" {
if err := os.Chmod(dir, 0700); err != nil {
return err
}
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
return f.Chmod(0600)
}
// getPrompt returns a dynamic prompt string like "user@host:dir $"
@@ -92,10 +306,10 @@ func getPrompt() string {
if home != "" && strings.HasPrefix(wd, home) {
// Replace home with ~
displayPath := "~" + strings.TrimPrefix(wd, home)
return fmt.Sprintf("%s@%s:%s $ ", username, hostname, displayPath)
return sanitize(fmt.Sprintf("%s@%s:%s $ ", username, hostname, displayPath))
}
return fmt.Sprintf("%s@%s:%s $ ", username, hostname, wd)
return sanitize(fmt.Sprintf("%s@%s:%s $ ", username, hostname, wd))
}
// shellCompleter implements readline.AutoCompleter for contextual completion
@@ -163,7 +377,7 @@ func pathExecutables(prefix string) []string {
}
for _, entry := range entries {
name := entry.Name()
if !strings.HasPrefix(name, prefix) {
if !strings.HasPrefix(name, prefix) || !isPrintable(name) {
continue
}
// Follow symlinks, only regular files with an executable bit count
@@ -254,6 +468,10 @@ func completeFilePath(line, prefix string) []string {
if strings.HasPrefix(name, ".") && !strings.HasPrefix(pattern, ".") {
continue
}
// Never insert control characters (e.g. escape sequences) into the line
if !isPrintable(name) {
continue
}
// Follow symlinks to decide whether this is a directory
if info, err := os.Stat(filepath.Join(dir, name)); err == nil && info.IsDir() {
name += "/"
@@ -265,13 +483,27 @@ func completeFilePath(line, prefix string) []string {
}
func main() {
// Ctrl+C sends SIGINT to the whole foreground process group. Catch it so
// that it only stops the running command and not the shell. (signal.Ignore
// would be inherited by the child processes.)
signal.Notify(make(chan os.Signal, 1), os.Interrupt)
histFile := historyFile()
if histFile != "" {
if err := prepareHistoryFile(histFile); err != nil {
fmt.Fprintln(os.Stderr, "History disabled:", err)
histFile = ""
}
}
// Create readline instance
l, err := readline.NewEx(&readline.Config{
Prompt: getPrompt(),
HistoryFile: "./gosh_history",
AutoComplete: newShellCompleter(),
InterruptPrompt: "^C",
EOFPrompt: "exit",
Prompt: getPrompt(),
HistoryFile: histFile,
DisableAutoSaveHistory: true,
AutoComplete: newShellCompleter(),
InterruptPrompt: "^C",
EOFPrompt: "exit",
})
if err != nil {
fmt.Fprintln(os.Stderr, "Error initializing readline:", err)
@@ -286,8 +518,12 @@ func main() {
line, err := l.Readline()
if err != nil {
// Ctrl+C discards the current line
if err == readline.ErrInterrupt {
continue
}
// Handle EOF (Ctrl+D)
if err == io.EOF || err == readline.ErrInterrupt {
if err == io.EOF {
fmt.Println()
break
}
@@ -300,8 +536,11 @@ func main() {
continue
}
// Add to history
l.SaveHistory(line)
// Add to history, unless the line starts with a space (like bash's
// HISTCONTROL=ignorespace) so that secrets can be kept out of it
if !strings.HasPrefix(line, " ") {
l.SaveHistory(line)
}
// Execute the input
if err := execInput(line); err != nil {
@@ -311,8 +550,9 @@ func main() {
}
func execInput(input string) error {
// Split the input separate the command and the arguments.
args, err := shlex.Split(input)
// Split the input into the command and its arguments, expanding
// variables and ~ on the way.
args, err := splitWords(input)
if err != nil {
return fmt.Errorf("invalid input: %w", err)
}
@@ -320,16 +560,6 @@ func execInput(input string) error {
return nil
}
// Expand environment variables in all arguments
for i, arg := range args {
args[i] = expandEnv(arg)
}
// Expand tilde in all arguments
for i, arg := range args {
args[i] = expandTilde(arg)
}
// Check for built-in commands.
switch args[0] {
case "cd":
@@ -357,9 +587,6 @@ func execInput(input string) error {
return os.Chdir(prevDir)
}
// Expand tilde in the path
path = expandTilde(path)
// Save current directory as previous before changing
previousDir = currentDir
@@ -423,12 +650,16 @@ Built-in commands:
help - Show this help
Features:
- Argument parsing with quotes and escapes
- Ctrl+D to exit, Ctrl+C to cancel
- Command history (up/down arrows)
- Argument parsing with quotes and escapes ('...' is literal,
"..." expands variables, \ escapes the next character)
- Ctrl+D to exit, Ctrl+C to cancel the current line or command
- Command history (up/down arrows), stored in
$XDG_STATE_HOME/gosh/history (default ~/.local/state/gosh/history,
override with $GOSH_HISTFILE); lines starting with a space are not saved
- Tab completion for commands and file paths
- Tilde expansion (~, ~/path)
- Environment variable expansion ($VAR, ${VAR})`)
- Tilde expansion (~, ~/path) at the start of unquoted words
- Environment variable expansion ($VAR, ${VAR}, ${VAR:-default});
using an unset variable is an error, use ${VAR:-} for an empty default`)
return nil
}