2021-03-20 22:49:15 +00:00
package fs
import (
2021-05-19 21:00:23 +00:00
"fmt"
2021-03-20 22:49:15 +00:00
"os"
2021-03-31 17:46:49 +00:00
"strings"
2021-03-20 22:49:15 +00:00
2021-05-01 17:38:01 +00:00
"github.com/yuin/gopher-lua"
"layeh.com/gopher-luar"
2021-03-20 22:49:15 +00:00
)
func Loader ( L * lua . LState ) int {
2021-04-28 11:26:23 +00:00
mod := L . SetFuncs ( L . NewTable ( ) , exports )
2021-03-20 22:49:15 +00:00
2021-04-28 11:26:23 +00:00
L . Push ( mod )
return 1
2021-03-20 22:49:15 +00:00
}
2021-10-16 14:21:05 +00:00
func luaErr ( L * lua . LState , code int ) {
2021-03-31 04:02:39 +00:00
// TODO: Error with a table, with path and error code
2021-03-31 11:32:47 +00:00
L . Error ( lua . LNumber ( code ) , 2 )
2021-03-31 03:56:37 +00:00
}
2021-03-20 22:49:15 +00:00
var exports = map [ string ] lua . LGFunction {
2021-10-16 14:21:05 +00:00
"cd" : fcd ,
"mkdir" : fmkdir ,
"stat" : fstat ,
2021-03-20 22:49:15 +00:00
}
2021-10-16 14:21:05 +00:00
// cd(dir)
// Changes directory to `dir`
func fcd ( L * lua . LState ) int {
2021-05-01 17:42:15 +00:00
path := L . CheckString ( 1 )
2021-03-20 22:49:15 +00:00
2021-03-31 17:46:49 +00:00
err := os . Chdir ( strings . TrimSpace ( path ) )
2021-03-31 03:56:37 +00:00
if err != nil {
2021-05-19 21:00:23 +00:00
switch e := err . ( * os . PathError ) . Err . Error ( ) ; e {
2021-03-31 03:56:37 +00:00
case "no such file or directory" :
2021-10-16 14:21:05 +00:00
luaErr ( L , 1 )
2021-09-29 02:55:08 +00:00
case "not a directory" :
2021-10-16 14:21:05 +00:00
luaErr ( L , 2 )
2021-05-19 21:00:23 +00:00
default :
2021-09-29 02:54:04 +00:00
fmt . Printf ( "Found unhandled error case: %s\n" , e )
fmt . Printf ( "Report this at https://github.com/Rosettea/Hilbish/issues with the title being: \"fs: unhandled error case %s\", and show what caused it.\n" , e )
2021-10-16 14:21:05 +00:00
luaErr ( L , 213 )
2021-03-31 03:56:37 +00:00
}
}
2021-03-20 22:49:15 +00:00
return 0
}
2021-10-16 14:21:05 +00:00
// mkdir(name, recursive)
// Makes a directory called `name`. If `recursive` is true, it will create its parent directories.
func fmkdir ( L * lua . LState ) int {
2021-05-01 17:42:15 +00:00
dirname := L . CheckString ( 1 )
2021-06-12 13:31:42 +00:00
recursive := L . ToBool ( 2 )
path := strings . TrimSpace ( dirname )
2021-04-09 22:10:18 +00:00
// TODO: handle error here
2021-06-12 13:31:42 +00:00
if recursive {
os . MkdirAll ( path , 0744 )
} else {
os . Mkdir ( path , 0744 )
}
2021-04-09 22:10:18 +00:00
return 0
}
2021-10-16 14:21:05 +00:00
// stat(path)
// Returns info about `path`
func fstat ( L * lua . LState ) int {
2021-05-01 17:42:15 +00:00
path := L . CheckString ( 1 )
2021-04-09 22:10:18 +00:00
// TODO: handle error here
pathinfo , _ := os . Stat ( path )
L . Push ( luar . New ( L , pathinfo ) )
return 1
}