This commit is contained in:
2025-12-07 09:24:48 -05:00
parent f5d928ebb9
commit 1de4ae1a24
11 changed files with 215 additions and 192 deletions

1
URGENT Normal file
View File

@@ -0,0 +1 @@
IT DOSN'T LOAD FES

View File

@@ -13,6 +13,10 @@ function M.fes(header, footer)
end end
end end
if site_config.favicon then
site_config.favicon = '<link rel="icon" type="image/x-icon" href="' .. site_config.favicon .. '">'
end
local self = { local self = {
version = site_config.version, version = site_config.version,
title = site_config.title, title = site_config.title,

View File

@@ -0,0 +1,5 @@
[app]
name = "archive"
version = "0.0.1"
authors = ["vx-clutch"]

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

View File

@@ -0,0 +1,8 @@
local fes = require("fes")
local site = fes.fes()
site.title = "archive"
site:h1("Hello, World!")
return site

View File

@@ -1,5 +1 @@
[app] dhasjkdhaskjdhaskhdajkshjk
name = "error"
version = "0.0.1"
authors = ["vx-clutch"]

5
examples/static/Fes.toml Normal file
View File

@@ -0,0 +1,5 @@
[app]
name = "static"
version = "0.0.1"
authors = ["vx-clutch"]

View File

@@ -0,0 +1 @@
this is some neat data

View File

@@ -0,0 +1,8 @@
local fes = require("fes")
local site = fes.fes()
site.title = "static"
site:h1("Hello, World!")
return site

View File

@@ -1,5 +1,4 @@
package new package new
import ( import (
"fmt" "fmt"
"os" "os"
@@ -10,8 +9,7 @@ import (
) )
func getName() string { func getName() string {
out, err := exec.Command("git", "config", "user.name").Output() out, err := exec.Command("git", "config", "user.name").Output(); if err == nil {
if err == nil {
s := strings.TrimSpace(string(out)) s := strings.TrimSpace(string(out))
if s != "" { if s != "" {
return s return s
@@ -24,36 +22,71 @@ func getName() string {
return "" return ""
} }
func Project(dir string) error { // func Project(dir string) error {
if err := os.MkdirAll(filepath.Join(dir, "www"), 0755); err != nil { // if err := os.MkdirAll(filepath.Join(dir, "www"), 0755); err != nil {
// return err
// }
// indexLua := filepath.Join(dir, "www", "index.lua")
// if _, err := os.Stat(indexLua); os.IsNotExist(err) {
// content := fmt.Sprintf(`local fes = require("fes")
// local site = fes.fes()
//
// site.title = "%s"
//
// site:h1("Hello, World!")
//
// return site
// `, dir)
// if err := os.WriteFile(indexLua, []byte(content), 0644); err != nil {
// return err
// }
// }
// indexFes := filepath.Join(dir, "Fes.toml")
// if _, err := os.Stat(indexFes); os.IsNotExist(err) {
// content := fmt.Sprintf(`[app]
//
// name = "%s"
// version = "0.0.1"
// authors = ["%s"]`, dir, getName())
// if err := os.WriteFile(indexFes, []byte(content), 0644); err != nil {
// return err
// }
// }
// fmt.Println("Created new project at", dir)
// return nil
// }
func write(path string, format string, args ...interface{}) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
panic(err)
}
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
panic(err)
}
defer f.Close()
_, err = fmt.Fprintf(f, format, args...)
return err return err
} }
indexLua := filepath.Join(dir, "www", "index.lua")
if _, err := os.Stat(indexLua); os.IsNotExist(err) {
content := fmt.Sprintf(`local fes = require("fes")
local site = fes.fes()
site.title = "%s" func Project(dir string) error {
if err := os.Mkdir(dir, 0755); err != nil {
return err
}
if err := os.Chdir(dir); err != nil {
return err
}
write("www/index.lua", `local fes = require("fes")
local site = fes.fes()
site:h1("Hello, World!") site:h1("Hello, World!")
return site return site`)
`, dir) write("Fes.toml", `[app]
if err := os.WriteFile(indexLua, []byte(content), 0644); err != nil {
return err
}
}
indexFes := filepath.Join(dir, "Fes.toml")
if _, err := os.Stat(indexFes); os.IsNotExist(err) {
content := fmt.Sprintf(`[app]
name = "%s" name = "%s"
version = "0.0.1" version = "0.0.1"
authors = ["%s"]`, dir, getName()) authors = ["%s"]`, dir, getName())
if err := os.WriteFile(indexFes, []byte(content), 0644); err != nil {
return err
}
}
fmt.Println("Created new project at", dir)
return nil return nil
} }

View File

@@ -2,19 +2,18 @@ package server
import ( import (
"fmt" "fmt"
"io/fs"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"github.com/fatih/color"
"github.com/gomarkdown/markdown" "github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html" "github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser" "github.com/gomarkdown/markdown/parser"
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
lua "github.com/yuin/gopher-lua" lua "github.com/yuin/gopher-lua"
"github.com/fatih/color"
"fes/src/config" "fes/src/config"
) )
@@ -24,56 +23,49 @@ type reqData struct {
params map[string]string params map[string]string
} }
func handleDir(entries []os.DirEntry, dir string, routes map[string]string, base string) error { func handleDir(entries []os.DirEntry, dir string, routes map[string]string, base string, isStatic bool) error {
for _, entry := range entries { for _, entry := range entries {
path := filepath.Join(dir, entry.Name())
if entry.IsDir() { if entry.IsDir() {
sub := filepath.Join(dir, entry.Name()) nextBase := joinBase(base, entry.Name())
subs, err := os.ReadDir(sub) subEntries, err := os.ReadDir(path)
if err != nil { if err != nil {
return fmt.Errorf("failed to read %s: %w", sub, err) return fmt.Errorf("failed to read directory %s: %w", path, err)
} }
var next string if err := handleDir(subEntries, path, routes, nextBase, isStatic); err != nil {
if base == "" {
next = "/" + entry.Name()
} else {
next = base + "/" + entry.Name()
}
if err := handleDir(subs, sub, routes, next); err != nil {
return err return err
} }
continue continue
} }
if strings.HasSuffix(entry.Name(), ".lua") { route := joinBase(base, entry.Name())
if !isStatic && strings.HasSuffix(entry.Name(), ".lua") {
name := strings.TrimSuffix(entry.Name(), ".lua") name := strings.TrimSuffix(entry.Name(), ".lua")
path := filepath.Join(dir, entry.Name())
if name == "index" { if name == "index" {
if base == "" { routes[basePath(base)] = path
routes["/"] = path routes[route] = path
routes["/index"] = path continue
} else {
routes[base] = path
routes[base+"/index"] = path
}
} else {
if base == "" {
routes["/"+name] = path
} else {
routes[base+"/"+name] = path
}
}
} else {
name := entry.Name()
path := filepath.Join(dir, entry.Name())
if base == "" {
routes["/"+name] = path
} else {
routes[base+"/"+name] = path
} }
route = joinBase(base, name)
} }
routes[route] = path
} }
return nil return nil
} }
func joinBase(base, name string) string {
if base == "" {
return "/" + name
}
return base + "/" + name
}
func basePath(base string) string {
if base == "" {
return "/"
}
return base
}
func fixMalformedToml(content string) string { func fixMalformedToml(content string) string {
re := regexp.MustCompile(`(?m)^(\s*\w+\s*=\s*)$`) re := regexp.MustCompile(`(?m)^(\s*\w+\s*=\s*)$`)
return re.ReplaceAllStringFunc(content, func(match string) string { return re.ReplaceAllStringFunc(content, func(match string) string {
@@ -103,17 +95,15 @@ func loadIncludeModules(L *lua.LState, includeDir string) *lua.LTable {
return app return app
} }
for _, e := range ents { for _, e := range ents {
if e.IsDir() { if e.IsDir() || !strings.HasSuffix(e.Name(), ".lua") {
continue continue
} }
name := e.Name() base := strings.TrimSuffix(e.Name(), ".lua")
if !strings.HasSuffix(name, ".lua") { path := filepath.Join(includeDir, e.Name())
continue
}
base := strings.TrimSuffix(name, ".lua")
path := filepath.Join(includeDir, name)
if err := L.DoFile(path); err != nil { if err := L.DoFile(path); err != nil {
fmt.Printf("Failed to load %s: %v\n", path, err) tbl := L.NewTable()
tbl.RawSetString("error", lua.LString(err.Error()))
app.RawSetString(base, tbl)
continue continue
} }
val := L.Get(-1) val := L.Get(-1)
@@ -127,35 +117,33 @@ func loadIncludeModules(L *lua.LState, includeDir string) *lua.LTable {
return app return app
} }
func loadLua(luaDir string, entry string, cfg *config.MyConfig, requestData reqData) (string, error) { func loadLua(luaDir, entry string, cfg *config.MyConfig, requestData reqData) (string, error) {
L := lua.NewState() L := lua.NewState()
defer L.Close() defer L.Close()
coreFiles, err := fs.ReadDir(config.Core, "core")
if err == nil {
for _, de := range coreFiles {
if de.IsDir() || !strings.HasSuffix(de.Name(), ".lua") {
continue
}
path := filepath.Join("core", de.Name())
fileData, err := config.Core.ReadFile(path)
if err != nil {
continue
}
L.DoString(string(fileData))
}
}
preloadLuaModule := func(name, path string) { preloadLuaModule := func(name, path string) {
L.PreloadModule(name, func(L *lua.LState) int { L.PreloadModule(name, func(L *lua.LState) int {
fileData, err := config.Core.ReadFile(path) data, err := config.Core.ReadFile(path)
if err != nil { if err != nil {
panic(err) tbl := L.NewTable()
tbl.RawSetString("error", lua.LString(err.Error()))
L.Push(tbl)
return 1
} }
if err := L.DoString(string(fileData)); err != nil { if _, err := L.LoadString(string(data)); err != nil {
panic(err) tbl := L.NewTable()
tbl.RawSetString("error", lua.LString(err.Error()))
L.Push(tbl)
return 1
} }
L.Push(L.Get(-1)) if err := L.CallByParam(lua.P{Fn: L.Get(-1), NRet: 1, Protect: true}); err != nil {
tbl := L.NewTable()
tbl.RawSetString("error", lua.LString(err.Error()))
L.Push(tbl)
return 1
}
ret := L.Get(-1)
L.Push(ret)
return 1 return 1
}) })
} }
@@ -166,42 +154,8 @@ func loadLua(luaDir string, entry string, cfg *config.MyConfig, requestData reqD
L.PreloadModule("fes", func(L *lua.LState) int { L.PreloadModule("fes", func(L *lua.LState) int {
mod := L.NewTable() mod := L.NewTable()
coreModules := []string{}
if ents, err := fs.ReadDir(config.Core, "core"); err == nil {
for _, e := range ents {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".lua") {
continue
}
coreModules = append(coreModules, strings.TrimSuffix(e.Name(), ".lua"))
}
}
for _, modName := range coreModules {
path := filepath.Join("core", modName+".lua")
fileData, err := config.Core.ReadFile(path)
if err != nil {
continue
}
if err := L.DoString(string(fileData)); err != nil {
continue
}
val := L.Get(-1)
L.Pop(1)
tbl, ok := val.(*lua.LTable)
if !ok || tbl == nil {
tbl = L.NewTable()
}
if modName == "builtin" {
tbl.ForEach(func(k, v lua.LValue) { mod.RawSet(k, v) })
} else {
mod.RawSetString(modName, tbl)
}
}
includeDir := filepath.Join(luaDir, "include") includeDir := filepath.Join(luaDir, "include")
mod.RawSetString("app", loadIncludeModules(L, includeDir)) mod.RawSetString("app", loadIncludeModules(L, includeDir))
if cfg != nil { if cfg != nil {
site := L.NewTable() site := L.NewTable()
site.RawSetString("version", lua.LString(cfg.App.Version)) site.RawSetString("version", lua.LString(cfg.App.Version))
@@ -213,7 +167,6 @@ func loadLua(luaDir string, entry string, cfg *config.MyConfig, requestData reqD
site.RawSetString("authors", authors) site.RawSetString("authors", authors)
mod.RawSetString("site", site) mod.RawSetString("site", site)
} }
bus := L.NewTable() bus := L.NewTable()
bus.RawSetString("url", lua.LString(requestData.path)) bus.RawSetString("url", lua.LString(requestData.path))
params := L.NewTable() params := L.NewTable()
@@ -222,12 +175,10 @@ func loadLua(luaDir string, entry string, cfg *config.MyConfig, requestData reqD
} }
bus.RawSetString("params", params) bus.RawSetString("params", params)
mod.RawSetString("bus", bus) mod.RawSetString("bus", bus)
mod.RawSetString("markdown_to_html", L.NewFunction(func(L *lua.LState) int { mod.RawSetString("markdown_to_html", L.NewFunction(func(L *lua.LState) int {
L.Push(lua.LString(markdownToHTML(L.ToString(1)))) L.Push(lua.LString(markdownToHTML(L.ToString(1))))
return 1 return 1
})) }))
L.Push(mod) L.Push(mod)
return 1 return 1
}) })
@@ -242,35 +193,31 @@ func loadLua(luaDir string, entry string, cfg *config.MyConfig, requestData reqD
L.SetGlobal("__fes_result", L.Get(-1)) L.SetGlobal("__fes_result", L.Get(-1))
if err := L.DoString("return tostring(__fes_result)"); err != nil { if err := L.DoString("return tostring(__fes_result)"); err != nil {
L.GetGlobal("__fes_result") return "", err
if s := L.ToString(-1); s != "" {
return s, nil
}
return "", nil
} }
if s := L.ToString(-1); s != "" { return L.ToString(-1), nil
return s, nil
}
return "", nil
} }
func Start(dir string) error { func Start(dir string) error {
os.Chdir(dir) if err := os.Chdir(dir); err != nil {
return fmt.Errorf("failed to change directory to %s: %w", dir, err)
}
dir = "." dir = "."
tomlDocument, err := os.ReadFile("Fes.toml") tomlDocument, err := os.ReadFile("Fes.toml")
if err != nil { if err != nil {
return err return fmt.Errorf("failed to read Fes.toml: %w", err)
} }
docStr := fixMalformedToml(string(tomlDocument)) docStr := fixMalformedToml(string(tomlDocument))
var cfg config.MyConfig var cfg config.MyConfig
err = toml.Unmarshal([]byte(docStr), &cfg) if err := toml.Unmarshal([]byte(docStr), &cfg); err != nil {
if err != nil { fmt.Printf("Warning: failed to parse Fes.toml: %v\n", err)
return fmt.Errorf("failed to parse Fes.toml: %w", err) cfg.App.Authors = []string{"unknown"}
cfg.App.Name = "unknown"
cfg.App.Version = "unknown"
} }
notFoundData := ` notFoundData := `
<html> <html>
<head><title>404 Not Found</title></head> <head><title>404 Not Found</title></head>
@@ -281,29 +228,32 @@ func Start(dir string) error {
</html> </html>
` `
if _, err := os.Stat(filepath.Join("www", "404.lua")); err == nil { if _, err := os.Stat(filepath.Join("www", "404.lua")); err == nil {
notFoundData, err = loadLua(dir, "www/404.lua", &cfg, reqData{}) if nf, err := loadLua(dir, "www/404.lua", &cfg, reqData{}); err == nil {
if err != nil { notFoundData = nf
panic(err)
} }
} else if _, err := os.Stat("www/404.html"); err == nil { } else if _, err := os.Stat("www/404.html"); err == nil {
buf, err := os.ReadFile("www/404.html") if buf, err := os.ReadFile("www/404.html"); err == nil {
if err != nil {
panic(err)
}
notFoundData = string(buf) notFoundData = string(buf)
} }
}
routes := make(map[string]string) routes := make(map[string]string)
if entries, err := os.ReadDir("www"); err == nil {
entries, err := os.ReadDir("www") if err := handleDir(entries, "www", routes, "", false); err != nil {
if err != nil { fmt.Printf("Warning: failed to handle www directory: %v\n", err)
return fmt.Errorf("failed to read www directory: %w", err) }
} }
handleDir(entries, "www", routes, "")
entries, err = os.ReadDir("static") if entries, err := os.ReadDir("static"); err == nil {
if err == nil { if err := handleDir(entries, "static", routes, "/static", true); err != nil {
handleDir(entries, "static", routes, "") fmt.Printf("Warning: failed to handle static directory: %v\n", err)
}
}
if entries, err := os.ReadDir("archive"); err == nil {
if err := handleDir(entries, "archive", routes, "/archive", true); err != nil {
fmt.Printf("Warning: failed to handle archive directory: %v\n", err)
}
} }
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
@@ -318,26 +268,38 @@ func Start(dir string) error {
} }
params := make(map[string]string) params := make(map[string]string)
for key, val := range r.URL.Query() { for k, val := range r.URL.Query() {
if len(val) > 0 { if len(val) > 0 {
params[key] = val[0] params[k] = val[0]
} }
} }
req := reqData{ req := reqData{
path: r.URL.Path, path: path,
params: params, params: params,
} }
fmt.Printf("> %s ", filepath.Base(lp)) fmt.Printf("> %s ", filepath.Base(lp))
data, err := loadLua(dir, lp, &cfg, req)
var data []byte
var err error
if strings.HasSuffix(lp, ".lua") {
var b string
b, err = loadLua(dir, lp, &cfg, req)
data = []byte(b)
} else {
data, err = os.ReadFile(lp)
}
if err != nil { if err != nil {
http.Error(w, fmt.Sprintf("Error loading page: %v", err), http.StatusInternalServerError) http.Error(w, fmt.Sprintf("Error loading page: %v", err), http.StatusInternalServerError)
color.Red("bad") color.Red("bad")
return return
} }
color.Green("ok") color.Green("ok")
w.Write([]byte(data)) w.Write(data)
}) })
fmt.Printf("Server is running on http://localhost:%d\n", *config.Port) fmt.Printf("Server is running on http://localhost:%d\n", *config.Port)