github.com/krzko/gosh@v0.0.0-20241128233202-5abd4ef06633/internal/shell/completion/completer.go (about)

     1  // internal/shell/completion/completer.go
     2  package completion
     3  
     4  import (
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  )
     9  
    10  type Completer struct {
    11  	builtins []string
    12  }
    13  
    14  func NewCompleter() *Completer {
    15  	return &Completer{
    16  		builtins: []string{"cd", "ls", "pwd", "http", "https", "history", "exit", "help"},
    17  	}
    18  }
    19  
    20  // Do implements the readline.AutoCompleter interface
    21  func (c *Completer) Do(line []rune, pos int) ([][]rune, int) {
    22  	lineStr := string(line[:pos])
    23  	if lineStr == "" {
    24  		return c.completeCommands(""), 0
    25  	}
    26  
    27  	words := strings.Fields(lineStr)
    28  	if len(words) == 0 {
    29  		return c.completeCommands(""), 0
    30  	}
    31  
    32  	wordStart := 0
    33  	if pos > 0 && !strings.HasSuffix(lineStr, " ") {
    34  		wordStart = strings.LastIndex(lineStr[:pos], " ") + 1
    35  	}
    36  
    37  	lastWord := lineStr[wordStart:pos]
    38  
    39  	// Command completion
    40  	if len(words) == 1 && lineStr == lastWord {
    41  		return c.completeCommands(lastWord), len(lastWord)
    42  	}
    43  
    44  	// Path completion for cd and ls
    45  	if len(words) > 0 && (words[0] == "cd" || words[0] == "ls") {
    46  		if len(words) == 1 || (len(words) == 2 && !strings.HasSuffix(lineStr, " ")) {
    47  			return c.completePaths(lastWord), len(lastWord)
    48  		}
    49  	}
    50  
    51  	return nil, 0
    52  }
    53  
    54  func (c *Completer) completeCommands(prefix string) [][]rune {
    55  	var suggestions [][]rune
    56  	for _, cmd := range c.builtins {
    57  		if strings.HasPrefix(cmd, prefix) {
    58  			suggestions = append(suggestions, []rune(cmd))
    59  		}
    60  	}
    61  	return suggestions
    62  }
    63  
    64  func (c *Completer) completePaths(prefix string) [][]rune {
    65  	var suggestions [][]rune
    66  
    67  	dir := "."
    68  	if prefix != "" {
    69  		dir = filepath.Dir(prefix)
    70  		if dir == "." && !strings.HasPrefix(prefix, ".") {
    71  			dir = prefix
    72  		}
    73  	}
    74  
    75  	base := filepath.Base(prefix)
    76  	if dir != "." && dir != prefix {
    77  		base = filepath.Base(prefix)
    78  	}
    79  
    80  	entries, err := os.ReadDir(dir)
    81  	if err != nil {
    82  		return nil
    83  	}
    84  
    85  	for _, entry := range entries {
    86  		name := entry.Name()
    87  		if strings.HasPrefix(name, base) {
    88  			fullPath := name
    89  			if dir != "." {
    90  				fullPath = filepath.Join(dir, name)
    91  			}
    92  			if entry.IsDir() {
    93  				fullPath += "/"
    94  			}
    95  			suggestions = append(suggestions, []rune(fullPath))
    96  		}
    97  	}
    98  
    99  	return suggestions
   100  }