I'm creating a program that will hopefully operate like linux terminal (basic commands) for learning purposes.
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
/*
type FileDir struct {
Name string
Permissions string
Owner string
ModifyDate int64
Size int32
IsDir bool
}
*/
func handleInput(input string) {
tokens := strings.Split(strings.TrimSpace(input), " ")
// cmd := tokens[0] // will be used later
options := make(map[string]int)
var positional []string
if len(tokens) > 1 {
// get options
for j := 1; j < len(tokens); j++ {
if strings.HasPrefix(tokens[j], "--") {
options[tokens[j][2:]] = 1
} else if strings.HasPrefix(tokens[j], "-") {
if len(tokens[j]) == 2 {
options[tokens[j][1:]] = 1
} else {
for _, flag := range tokens[j][1:] {
options[string(flag)] = 1
}
}
} else {
positional = append(positional, tokens[j])
}
}
}
// handling of above input, based on cmd
/* switch cmd {
// ...
case "ls" {
_, hiddenFlag := options["a"]
_, hiddenBig := options["all"]
_, long := options["l"]
_, human := options["h"]
if len(tokens) == 1 {
contents := getContentNames(false) // returns []string
sort.Strings(contents)
fmt.Println(strings.Join(contents, " "))
} else {
// TODO details
if long {
contents := getContents(hiddenFlag || hiddenBig) // returns []FileDir
sort.Sort(ByName(contents))
for _, fileDir := range contents {
d := "-"
if fileDir.IsDir {
d = "d"
}
var s string
if human {
s = formatBytes(fileDir.Size)
} else {
s = fmt.Sprintf("%7d", fileDir.Size)
}
// WIP
fmt.Printf("%s%s %s %s %s MON DY HH:MM %s\n", d, fileDir.Permissions, fileDir.Owner, fileDir.Owner, s, fileDir.Name)
}
} else {
contents := getContentNames(hiddenFlag || hiddenBig)
sort.Strings(contents)
fmt.Println(strings.Join(contents, " "))
}
}
}
// ...
}*/
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
var userInput string
for {
fmt.Printf("[root@FAKE /]$ ")
scanner.Scan()
userInput = scanner.Text()
if userInput == "exit" || userInput == "quit" || userInput == "logout" {
break
}
handleInput(userInput)
}
}
At this time I want to know if the parsing of options I'm currently doing is the most optimal/efficient way for basic linux commands (ls (-alhs
vs -l
vs -l -a
), man [cmd], cd [loc], tail -f #, etc) so that flags together and/or separate will be able to be later handled. I did include my current handling of the command ls
but this section is WIP. If there is a radical change to the way I've done things it might be nice to show how it would optimize of ls
handling (but this isn't necessary)
cmd
,options
, etc) which are currently unused are used, and how I plan on using parsed input \$\endgroup\$