Compare commits

...

17 Commits

Author SHA1 Message Date
TorchedSammy 09a4cb4787 chore: update version 2021-03-30 19:50:35 -04:00
TorchedSammy c5a58b1d01 chore: update todo 2021-03-30 19:50:02 -04:00
TorchedSammy cb6f17c8fa details: make triangle in prompt change color based on command result 2021-03-30 19:48:37 -04:00
TorchedSammy f20be5153f feat: add hooks/events 2021-03-30 19:47:02 -04:00
TorchedSammy 352c5f73a8 chore: merge from master 2021-03-28 19:31:29 -04:00
TorchedSammy e561be0c9f chore: comments everywhere 2021-03-28 18:58:58 -04:00
TorchedSammy 479968f79e fix: dont replace ^^ in commands before, or in quotes 2021-03-28 18:15:51 -04:00
TorchedSammy b735421af8 feat: add ^^ for last command 2021-03-28 17:51:15 -04:00
TorchedSammy d945d510f7 feat: printf-like formatting for prompt 2021-03-28 17:11:57 -04:00
TorchedSammy 8b7c7e707a chore: fix todo 2021-03-26 11:41:07 -04:00
TorchedSammy 7486d58465 fix: merge conflicts 2021-03-26 01:14:25 -04:00
TorchedSammy aea035fe41 wip(feat): bait package for hooks 2021-03-26 01:12:55 -04:00
TorchedSammy c5fa238156 wip: get prompt from format function 2021-03-26 01:06:14 -04:00
TorchedSammy 4a08ab7837 chore: update todo 2021-03-24 23:50:33 -04:00
TorchedSammy 1ee4c10a89 change: use c style formatting verbs 2021-03-24 23:32:13 -04:00
TorchedSammy da9cfd5e04 chore: change default config 2021-03-24 20:59:36 -04:00
TorchedSammy 913d6486ac fix: merge conflicts; dont set /bin/zsh explicitly unless used with flag (for neofetch to use hilbish :)) 2021-03-24 20:58:31 -04:00
4 changed files with 184 additions and 39 deletions

View File

@ -1,6 +1,21 @@
-- Default Hilbish config
ansikit = require 'ansikit'
bait = require 'bait'
prompt(ansikit.text('λ {bold}{cyan}'..os.getenv('USER')..' >{magenta}>{cyan}>{reset} '))
function doPrompt(fail)
prompt(ansikit.text(
'{blue}%u {cyan}%d ' .. (fail and '{red}' or '{green}') .. '∆{reset} '
))
end
doPrompt()
bait.catch('command.fail', function()
doPrompt(true)
end)
bait.catch('command.success', function()
doPrompt()
end)
--hook("tab complete", function ())

16
TODO.md
View File

@ -1,8 +1,8 @@
[x] Configuration
[x] Make default config if missing
[x] Tab completion
[x] Custom commands via the shell
[ ] Confirmed windows support
[ ] Readme badges
[ ] Hooks
[x] Aliases
- [x] Configuration
- [x] Make default config if missing
- [x] Tab completion
- [x] Custom commands via the shell
- [ ] Confirmed windows support
- [ ] Readme badges
- [x] Hooks
- [x] Aliases

View File

@ -0,0 +1,35 @@
package bait
import (
"github.com/chuckpreslar/emission"
"github.com/yuin/gopher-lua"
"layeh.com/gopher-luar"
)
type Bait struct{
Em *emission.Emitter
}
func New() Bait {
return Bait{
Em: emission.NewEmitter(),
}
}
func (b *Bait) Loader(L *lua.LState) int {
mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{})
L.SetField(mod, "throw", luar.New(L, b.throw))
L.SetField(mod, "catch", luar.New(L, b.catch))
L.Push(mod)
return 1
}
func (b *Bait) throw(name string, args ...interface{}) {
b.Em.Emit(name, args...)
}
func (b *Bait) catch(name string, catcher func(interface{})) {
b.Em.On(name, catcher)
}

155
main.go
View File

@ -4,8 +4,7 @@ import (
"bufio"
"fmt"
"os"
_ "os/exec"
_ "os/user"
"os/user"
"syscall"
"os/signal"
"strings"
@ -13,6 +12,7 @@ import (
"context"
lfs "hilbish/golibs/fs"
cmds "hilbish/golibs/commander"
hooks "hilbish/golibs/bait"
"github.com/akamensky/argparse"
"github.com/bobappleyard/readline"
@ -23,21 +23,31 @@ import (
)
const version = "0.1.2"
const version = "0.2.0"
var l *lua.LState
// User's prompt, this will get set when lua side is initialized
var prompt string
// Map of builtin/custom commands defined in the commander lua module
var commands = map[string]bool{}
// Command aliases
var aliases = map[string]string{}
var bait hooks.Bait
func main() {
parser := argparse.NewParser("hilbish", "A shell for lua and flower lovers")
verflag := parser.Flag("v", "version", &argparse.Options{
Required: false,
Help: "prints hilbish version",
Help: "Prints Hilbish version",
})
setshflag := parser.Flag("S", "set-shell-env", &argparse.Options{
Required: false,
Help: "Sets $SHELL to Hilbish's executed path",
})
err := parser.Parse(os.Args)
// If invalid flags or --help/-h,
if err != nil {
// Print usage
fmt.Print(parser.Usage(err))
os.Exit(0)
}
@ -47,21 +57,28 @@ func main() {
os.Exit(0)
}
os.Setenv("SHELL", os.Args[0])
input, err := os.ReadFile(".hilbishrc.lua")
if err != nil {
input, err = os.ReadFile("/usr/share/hilbish/.hilbishrc.lua")
if err != nil {
fmt.Println("could not find .hilbishrc.lua or /usr/share/hilbish/.hilbishrc.lua")
return
}
}
// Set $SHELL if the user wants to
if *setshflag { os.Setenv("SHELL", os.Args[0]) }
homedir, _ := os.UserHomeDir()
// If user's config doesn't exixt,
if _, err := os.Stat(homedir + "/.hilbishrc.lua"); os.IsNotExist(err) {
// Read default from current directory
// (this is assuming the current dir is Hilbish's git)
input, err := os.ReadFile(".hilbishrc.lua")
if err != nil {
// If it wasnt found, go to "real default"
input, err = os.ReadFile("/usr/share/hilbish/.hilbishrc.lua")
if err != nil {
fmt.Println("could not find .hilbishrc.lua or /usr/share/hilbish/.hilbishrc.lua")
return
}
}
// Create it using either default config we found
err = os.WriteFile(homedir + "/.hilbishrc.lua", input, 0644)
if err != nil {
// If that fails, bail
fmt.Println("Error creating config file")
fmt.Println(err)
return
@ -72,41 +89,43 @@ func main() {
LuaInit()
readline.Completer = readline.FilenameCompleter
for {
//user, _ := user.Current()
//dir, _ := os.Getwd()
//host, _ := os.Hostname()
//reader := bufio.NewReader(os.Stdin)
//fmt.Printf(prompt)
cmdString, err := readline.String(prompt)
cmdString, err := readline.String(fmtPrompt())
if err == io.EOF {
// Exit if user presses ^D (ctrl + d)
fmt.Println("")
break
}
if err != nil {
// If we get a completely random error, print
fmt.Fprintln(os.Stderr, err)
}
// I have no idea if we need this anymore
cmdString = strings.TrimSuffix(cmdString, "\n")
// First try to run user input in Lua
err = l.DoString(cmdString)
if err == nil {
// If it succeeds, add to history and prompt again
readline.AddHistory(cmdString)
continue
}
cmdArgs := splitInput(cmdString)
// Split up the input
cmdArgs, cmdString := splitInput(cmdString)
// If there's actually no input, prompt again
if len(cmdArgs) == 0 { continue }
// If alias was found, use command alias
if aliases[cmdArgs[0]] != "" {
cmdString = aliases[cmdArgs[0]] + strings.Trim(cmdString, cmdArgs[0])
//cmdArgs := splitInput(cmdString)
execCommand(cmdString)
continue
}
// If command is defined in Lua then run it
if commands[cmdArgs[0]] {
err := l.CallByParam(lua.P{
Fn: l.GetField(
@ -124,12 +143,15 @@ func main() {
readline.AddHistory(cmdString)
continue
}
// Last option: use sh interpreter
switch cmdArgs[0] {
case "exit":
os.Exit(0)
default:
err := execCommand(cmdString)
if err != nil {
// If input is incomplete, start multiline prompting
if syntax.IsIncomplete(err) {
sb := &strings.Builder{}
for {
@ -139,14 +161,49 @@ func main() {
}
}
} else {
if code, ok := interp.IsExitStatus(err); ok {
if code > 0 {
bait.Em.Emit("command.fail", code)
}
}
fmt.Fprintln(os.Stderr, err)
}
} else {
bait.Em.Emit("command.success", nil)
}
}
}
}
// This semi cursed function formats our prompt (obviously)
func fmtPrompt() string {
user, _ := user.Current()
host, _ := os.Hostname()
cwd, _ := os.Getwd()
cwd = strings.Replace(cwd, user.HomeDir, "~", 1)
args := []string{
"d", cwd,
"h", host,
"u", user.Name,
}
for i, v := range args {
if i % 2 == 0 {
args[i] = "%" + v
}
}
r := strings.NewReplacer(args...)
nprompt := r.Replace(prompt)
return nprompt
}
func StartMultiline(prev string, sb *strings.Builder) bool {
// sb fromt outside is passed so we can
// save input from previous prompts
if sb.String() == "" { sb.WriteString(prev + "\n") }
fmt.Printf("... ")
@ -155,6 +212,7 @@ func StartMultiline(prev string, sb *strings.Builder) bool {
cont, err := reader.ReadString('\n')
if err == io.EOF {
// Exit when ^D
fmt.Println("")
return true
}
@ -166,36 +224,64 @@ func StartMultiline(prev string, sb *strings.Builder) bool {
return false
}
return true
return true
}
func splitInput(input string) []string {
func splitInput(input string) ([]string, string) {
// end my suffering
// TODO: refactor this garbage
quoted := false
startlastcmd := false
lastcmddone := false
cmdArgs := []string{}
sb := &strings.Builder{}
cmdstr := &strings.Builder{}
lastcmd := readline.GetHistory(readline.HistorySize() - 1)
for _, r := range input {
if r == '"' {
// start quoted input
// this determines if other runes are replaced
quoted = !quoted
// dont add back quotes
//sb.WriteRune(r)
} else if !quoted && r == '~' {
// if not in quotes and ~ is found then make it $HOME
sb.WriteString(os.Getenv("HOME"))
} else if !quoted && r == ' ' {
// if not quoted and there's a space then add to cmdargs
cmdArgs = append(cmdArgs, sb.String())
sb.Reset()
} else if !quoted && r == '^' && startlastcmd && !lastcmddone {
// if ^ is found, isnt in quotes and is
// the second occurence of the character and is
// the first time "^^" has been used
cmdstr.WriteString(lastcmd)
sb.WriteString(lastcmd)
startlastcmd = !startlastcmd
lastcmddone = !lastcmddone
continue
} else if !quoted && r == '^' && !lastcmddone {
// if ^ is found, isnt in quotes and is the
// first time of starting "^^"
startlastcmd = !startlastcmd
continue
} else {
sb.WriteRune(r)
}
cmdstr.WriteRune(r)
}
if sb.Len() > 0 {
cmdArgs = append(cmdArgs, sb.String())
}
readline.AddHistory(input)
return cmdArgs
return cmdArgs, cmdstr.String()
}
// Run command in sh interpreter
func execCommand(cmd string) error {
file, err := syntax.NewParser().Parse(strings.NewReader(cmd), "")
if err != nil {
@ -204,11 +290,12 @@ func execCommand(cmd string) error {
runner, _ := interp.New(
interp.StdIO(os.Stdin, os.Stdout, os.Stderr),
)
runner.Run(context.TODO(), file)
err = runner.Run(context.TODO(), file)
return nil
return err
}
// do i even have to say
func HandleSignals() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
@ -218,6 +305,7 @@ func HandleSignals() {
}
func LuaInit() {
// TODO: Move to lua.go
l = lua.NewState()
l.OpenLibs()
@ -225,9 +313,11 @@ func LuaInit() {
l.SetGlobal("prompt", l.NewFunction(hshprompt))
l.SetGlobal("alias", l.NewFunction(hshalias))
// Add fs module to Lua
l.PreloadModule("fs", lfs.Loader)
commander := cmds.New()
// When a command from Lua is added, register it for use
commander.Events.On("commandRegister",
func (cmdName string, cmd *lua.LFunction) {
commands[cmdName] = true
@ -240,6 +330,10 @@ func LuaInit() {
l.PreloadModule("commander", commander.Loader)
bait = hooks.New()
l.PreloadModule("bait", bait.Loader)
// Add more paths that Lua can require from
l.DoString("package.path = package.path .. ';./libs/?/init.lua;/usr/share/hilbish/libs/?/init.lua'")
err := l.DoFile("/usr/share/hilbish/preload.lua")
@ -252,6 +346,7 @@ func LuaInit() {
}
homedir, _ := os.UserHomeDir()
// Run config
err = l.DoFile(homedir + "/.hilbishrc.lua")
if err != nil {
panic(err)