Skip to content

Commit

Permalink
Adding standard shell commands ls, cwd, mkdir, mv, cd ... to devops c…
Browse files Browse the repository at this point in the history
…ontext
  • Loading branch information
refaktor committed Apr 6, 2024
1 parent 60b2478 commit f937891
Show file tree
Hide file tree
Showing 6 changed files with 147 additions and 19 deletions.
3 changes: 3 additions & 0 deletions env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ type ProgramState struct {
SkipFlag bool
InErrHandler bool
ScriptPath string // holds the path to the script that is being imported (doed) currently
WorkingPath string // holds the path to CWD (can be changed in program with specific functions)
}

func NewProgramState(ser TSeries, idx *Idxs) *ProgramState {
Expand All @@ -284,6 +285,7 @@ func NewProgramState(ser TSeries, idx *Idxs) *ProgramState {
false,
false,
"",
"",
}
return &ps
}
Expand All @@ -306,6 +308,7 @@ func NewProgramStateNEW() *ProgramState {
false,
false,
"",
"",
}
return &ps
}
Expand Down
2 changes: 1 addition & 1 deletion evaldo/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -7424,7 +7424,7 @@ func RegisterBuiltins(ps *env.ProgramState) {
RegisterBuiltins2(Builtins_smtpd, ps, "smtpd")
RegisterBuiltins2(Builtins_mail, ps, "mail")
RegisterBuiltinsInContext(Builtins_math, ps, "math")
RegisterBuiltinsInContext(Builtins_ps, ps, "devops")
RegisterBuiltinsInContext(Builtins_devops, ps, "devops")
// ## Archived modules
// RegisterBuiltins2(Builtins_gtk, ps, "gtk")
// RegisterBuiltins2(Builtins_nats, ps, "nats")
Expand Down
128 changes: 122 additions & 6 deletions evaldo/builtins_psutil.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
//go:build b_psutil
// +build b_psutil
//go:build b_devops
// +build b_devops

package evaldo

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"

Expand All @@ -20,7 +23,120 @@ import (
// In request we return a raw-map, because it's very inside loop call, this is sparse call, and we get tons of fields, so it would be best
// to turn them to normal Rye map (which is now Env / later Context or something like it), and they query it from Rye.

var Builtins_ps = map[string]*env.Builtin{
func FileExists(filePath string) int {
_, err := os.Stat(filePath)
if err != nil {
if os.IsNotExist(err) {
return 0 // fmt.Println("File does not exist")
} else {
return -1 // fmt.Println("Error checking file:", err)
}
} else {
return 1
}
}

var Builtins_devops = map[string]*env.Builtin{

"cd": {
Argsn: 1,
Doc: "Changes current directory.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
switch path := arg0.(type) {
case env.Uri:
new := filepath.Join(filepath.Dir(ps.WorkingPath), path.GetPath())
res := FileExists(new)
if res == 1 {
ps.WorkingPath = filepath.Join(filepath.Dir(ps.WorkingPath), path.GetPath())
return arg0
} else if res == 0 {
return MakeBuiltinError(ps, "Path doesn't exist", "cd")
} else {
return MakeBuiltinError(ps, "Error determining if path exists", "cd")
}
// TODO -- check if it exists
default:
return *MakeArgError(ps, 1, []env.Type{env.UriType}, "cd")
}
},
},

"mkdir": {
Argsn: 1,
Doc: "Creates a directory.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
switch path := arg0.(type) {
case env.Uri:
newDir := filepath.Join(filepath.Dir(ps.WorkingPath), path.GetPath())
err := os.Mkdir(newDir, 0755) // Create directory with permissions 0755
if err != nil {
return *MakeBuiltinError(ps, "Error creating directory: "+err.Error(), "mkdir")
} else {
return arg0
}
default:
return *MakeArgError(ps, 1, []env.Type{env.UriType}, "mkdir")
}
},
},

"mv": {
Argsn: 2,
Doc: "Creates a directory.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
switch path := arg0.(type) {
case env.Uri:
switch path2 := arg1.(type) {
case env.Uri:
old := filepath.Join(filepath.Dir(ps.WorkingPath), path.GetPath())
new := filepath.Join(filepath.Dir(ps.WorkingPath), path2.GetPath())
err := os.Rename(old, new)
if err != nil {
fmt.Println("Error renaming file:", err)
return *MakeBuiltinError(ps, "Error renaming file: "+err.Error(), "mv")
} else {
return arg1
}
default:
return *MakeArgError(ps, 1, []env.Type{env.UriType}, "mkdir")
}
default:
return *MakeArgError(ps, 1, []env.Type{env.UriType}, "mkdir")
}
},
},

"cwd": {
Argsn: 0,
Doc: "Returns current working directory.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
return *env.NewUri1(ps.Idx, "file://"+ps.WorkingPath)
},
},

"ls": {
Argsn: 0,
Doc: "Returns current working directory.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {

files, err := ioutil.ReadDir(ps.WorkingPath + "/")
if err != nil {
return *MakeBuiltinError(ps, "Error reading directory:"+err.Error(), "ls")
}

items := make([]env.Object, len(files))

for i, file := range files {
// fmt.Println(file.Name()) // Print only file/directory names

items[i] = *env.NewUri1(ps.Idx, "file://"+file.Name())
}
return *env.NewBlock(*env.NewTSeries(items))

},
},

// GOPSUTIL

"host-info?": {
Argsn: 0,
Expand Down Expand Up @@ -78,7 +194,7 @@ var Builtins_ps = map[string]*env.Builtin{
r.Data["1"] = *env.NewDecimal(v.Load1)
r.Data["5"] = *env.NewDecimal(v.Load5)
r.Data["15"] = *env.NewDecimal(v.Load15)
return r
return *r
},
},
"virtual-memory?": {
Expand Down Expand Up @@ -139,7 +255,7 @@ var Builtins_ps = map[string]*env.Builtin{
for i, p := range pids {
pids2[i] = env.NewInteger(int64(p))
}
return env.NewBlock(*env.NewTSeries(pids2))
return *env.NewBlock(*env.NewTSeries(pids2))
},
},
"processes?": {
Expand Down Expand Up @@ -171,7 +287,7 @@ var Builtins_ps = map[string]*env.Builtin{
processSpreadsheetAdd(s, process)
return s.Rows[0].ToDict()
default:
return MakeArgError(ps, 1, []env.Type{env.IntegerType}, "process")
return *MakeArgError(ps, 1, []env.Type{env.IntegerType}, "process")
}
},
},
Expand Down
6 changes: 3 additions & 3 deletions evaldo/builtins_psutil_not.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//go:build !b_psutil
// +build !b_psutil
//go:build !b_devops
// +build !b_devops

package evaldo

import (
"github.com/refaktor/rye/env"
)

var Builtins_ps = map[string]*env.Builtin{}
var Builtins_devops = map[string]*env.Builtin{}
21 changes: 15 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ var CODE []any
// NEW FLASGS HANDLING

var (
// fileName = flag.String("file", "", "Path to the Rye file (default: none)")
// fileName = flag.String("fiimle", "", "Path to the Rye file (default: none)")
do = flag.String("do", "", "Evaluates code after it loads a file or last save.")
silent = flag.Bool("silent", false, "Console doesn't display return values")
// quit = flag.Bool("quit", false, "Quits after executing.")
Expand All @@ -75,11 +75,13 @@ func main() {
fmt.Println(" [some/path]/.\n Executes a main.rye on some path")
fmt.Println("\n \033[1mCommands:\033[0m (optional)")
fmt.Println(" cont\n Continue console from the last save")
fmt.Println(" here\n Starts in Rye here mode")
fmt.Println(" here\n Starts in Rye here mode (wip)")
fmt.Println(" \033[1mExamples:\033[0m")
fmt.Println("\033[33m rye \033[36m# enters console/REPL")
fmt.Println("\033[33m rye cont \033[36m# loads last saved state and enters console")
fmt.Println("\033[33m rye -do 'print 10 + 10' cont \033[36m# loads last saved state, evaluates do code and enters console")
fmt.Println("\033[33m rye -do \"print 33 * 42\" \033[36m# evaluates the do code")
fmt.Println("\033[33m rye -do 'name: \"Jim\"' console \033[36m# evaluates the do code and enters console")
fmt.Println("\033[33m rye cont \033[36m# continues/loads last saved state and enters console")
fmt.Println("\033[33m rye -do 'print 10 + 10' cont \033[36m# continues/loads last saved state, evaluates do code and enters console")
fmt.Println("\033[33m rye filename.rye \033[36m# evaluates filename.rye")
fmt.Println("\033[33m rye . \033[36m# evaluates main.rye in current directory")
fmt.Println("\033[33m rye some/path/. \033[36m# evaluates main.rye in some/path/")
Expand Down Expand Up @@ -125,7 +127,11 @@ func main() {
main_rye_file(ryeFile, false, true, *console, code)
}
} else {
main_rye_repl(os.Stdin, os.Stdout, true, false)
if *do != "" {
main_rye_file("", false, true, *console, code)
} else {
main_rye_repl(os.Stdin, os.Stdout, true, false)
}
}
}
}
Expand Down Expand Up @@ -390,12 +396,14 @@ func main_rye_file(file string, sig bool, subc bool, interactive bool, code stri
password := string(bytePassword)

content = util.ReadSecure(file, password)
} else {
} else if file != "" {
bcontent, err := os.ReadFile(file)
if err != nil {
log.Fatal(err)
}
content = string(bcontent)
} else {
content = ""
}

if info {
Expand All @@ -412,6 +420,7 @@ func main_rye_file(file string, sig bool, subc bool, interactive bool, code stri

ps := env.NewProgramStateNEW()
ps.ScriptPath = file
ps.WorkingPath, _ = os.Getwd() // TODO -- WHAT SHOULD WE DO IF GETWD FAILS?
evaldo.RegisterBuiltins(ps)
contrib.RegisterBuiltins(ps, &evaldo.BuiltinNames)
// ctx := ps.Ctx
Expand Down
6 changes: 3 additions & 3 deletions tests/basics.rye
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ section "Printing functions"
{
stdout { prns 123 } "123 "
}
group "print\val"
mold\nowrap ?print\val
group "printv"
mold\nowrap ?printv
{ { object } }
{
stdout { print\val 33 "value is: {{}}" } "value is: 33" + newline
stdout { printv 33 "value is: {}" } "value is: 33" + newline
; stdout { print\val "OK" "value is: {{}}" } "value is: 33" + newline ; TODO-BUG quotes the string
; stdout { { "Jane Austen" } print\val "Hello {{}}!" } "value is: 33" + newline
}
Expand Down

0 comments on commit f937891

Please sign in to comment.