Skip to content

Commit

Permalink
fix: dynamic paths and other nit-picks
Browse files Browse the repository at this point in the history
  • Loading branch information
barelyhuman committed Apr 25, 2024
1 parent 8a9b929 commit ce1457e
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 32 deletions.
3 changes: 1 addition & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

.PHONY.: all

all: clean build
Expand All @@ -16,7 +15,7 @@ docs: build
./alvu --path="docs" --baseurl="/alvu/" --highlight --hard-wrap=false

docs_dev: build
./alvu --highlight --hard-wrap=false --serve --path='./docs'
DEBUG=true ./alvu --highlight --hard-wrap=false --serve --path='./docs'

pages: docs
rm -rf alvu
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func main() {
&cli.StringFlag{
Name: "port",
Usage: "port to use for serving the application",
Value: ":3000",
Value: "3000",
Aliases: []string{"p"},
},
},
Expand Down
58 changes: 41 additions & 17 deletions pkg/alvu/alvu.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package alvu
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -103,7 +104,12 @@ func (ac *AlvuConfig) Run() error {
}

ac.HandlePublicFiles(publicFiles)
return ac.FlushFiles(processedFiles)
err = ac.FlushFiles(processedFiles)
if err != nil {
return err
}

return ac.StartServer()
}

func (ac *AlvuConfig) ReadLayout() string {
Expand All @@ -128,7 +134,7 @@ func (ac *AlvuConfig) HandlePublicFiles(files []string) (err error) {
file := v
go func() {
destFile := filepath.Clean(file)
destFile = strings.TrimPrefix(destFile, "public")
destFile = strings.TrimPrefix(destFile, filepath.Join(ac.RootPath, "public"))
destFile = filepath.Join(ac.OutDir, destFile)
os.MkdirAll(filepath.Dir(destFile), os.ModePerm)

Expand All @@ -148,6 +154,8 @@ func (ac *AlvuConfig) createTransformedFile(filePath string, content string) (tr
if err != nil {
return
}
defer fileWriter.Close()

_, err = fileWriter.WriteString(content)
if err != nil {
return
Expand All @@ -170,14 +178,16 @@ func (ac *AlvuConfig) FlushFiles(files []HookedFile) error {
for i := range files {
hookedFile := files[i]
originalDir, baseFile := filepath.Split(hookedFile.SourcePath)
newDir := strings.TrimPrefix(originalDir, "pages")
newDir := strings.TrimPrefix(originalDir, filepath.Join(ac.RootPath, "pages"))
fileWithNewExtension := strings.TrimSuffix(baseFile, hookedFile.Extension) + ".html"
destFile := filepath.Join(
ac.OutDir,
newDir,
fileWithNewExtension,
)

ac.logger.Debug(fmt.Sprintf("originalFile:%v, desFile: %v", hookedFile.SourcePath, destFile))

err := os.MkdirAll(filepath.Dir(destFile), os.ModePerm)
if err != nil {
return err
Expand All @@ -199,11 +209,15 @@ func (ac *AlvuConfig) FlushFiles(files []HookedFile) error {
}
}

replaced, _ := ac.injectInSlot(
replaced, err := ac.injectInSlot(
ac.ReadLayout(),
string(hookedFile.content),
)

if err != nil {
return err
}

template := templateHTML.New("temporaryTemplate")
template = template.Funcs(templateHTML.FuncMap{
"transform": func(extension string, content string) templateHTML.HTML {
Expand Down Expand Up @@ -289,6 +303,29 @@ func (ac *AlvuConfig) ReadDir(dir string) (filepaths []string, err error) {
return sanitizedCollection, nil
}

func (ac *AlvuConfig) injectInSlot(htmlString string, replacement string) (string, error) {
if hasLegacySlot(htmlString) {
return injectInLegacySlot(htmlString, replacement), nil
}
slotStartPos := strings.Index(htmlString, slotStartTag)
slotEndPos := strings.Index(htmlString, slotEndTag)
if slotStartPos == -1 && slotEndPos == -1 {
return htmlString, nil
}
baseString := strings.Replace(htmlString, slotEndTag, "", slotEndPos)
return strings.Replace(baseString, slotStartTag, replacement, slotStartPos), nil
}

func (ac *AlvuConfig) StartServer() error {
if !ac.Serve {
return nil
}

http.Handle("/", http.FileServer(http.Dir(ac.OutDir)))
ac.logger.Info(fmt.Sprintf("Starting Server - %v:%v", "http://localhost", ac.PortNumber))
return http.ListenAndServe(fmt.Sprintf(":%v", ac.PortNumber), nil)
}

func recursiveRead(dir string) (filepaths []string, err error) {
dirEntry, err := os.ReadDir(
dir,
Expand All @@ -313,19 +350,6 @@ func recursiveRead(dir string) (filepaths []string, err error) {
return
}

func (ac *AlvuConfig) injectInSlot(htmlString string, replacement string) (string, error) {
if hasLegacySlot(htmlString) {
return injectInLegacySlot(htmlString, replacement), nil
}
slotStartPos := strings.Index(htmlString, slotStartTag)
slotEndPos := strings.Index(htmlString, slotEndTag)
if slotStartPos == -1 && slotEndPos == -1 {
return htmlString, nil
}
baseString := strings.Replace(htmlString, slotEndTag, "", slotEndPos)
return strings.Replace(baseString, slotStartTag, replacement, slotStartPos), nil
}

func hasLegacySlot(htmlString string) bool {
return strings.Contains(htmlString, contentTag)
}
Expand Down
29 changes: 18 additions & 11 deletions pkg/alvu/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,24 +42,26 @@ type HookedFile struct {
}

func (h *Hooks) Load() {
hookDir := filepath.Clean(filepath.Join(h.ac.RootPath, h.ac.HookDir))
h.ac.logger.Debug(fmt.Sprintf("hookDir: %v\n", hookDir))
hookFiles := []string{}
folderInfo, err := os.Stat(h.ac.HookDir)
_, err := os.Stat(hookDir)
if err != nil {
if os.IsNotExist(err) {
return
}
readHookDirError(err, h.ac.HookDir, h.ac.logger)
readHookDirError(err, hookDir, h.ac.logger)
}

file, err := os.Open(folderInfo.Name())
readHookDirError(err, h.ac.HookDir, h.ac.logger)
file, err := os.Open(hookDir)
readHookDirError(err, hookDir, h.ac.logger)
childs, err := file.Readdirnames(1)
readHookDirError(err, h.ac.HookDir, h.ac.logger)
readHookDirError(err, hookDir, h.ac.logger)
if len(childs) == 0 {
return
}

filepath.WalkDir(h.ac.HookDir, func(path string, d fs.DirEntry, err error) error {
filepath.WalkDir(hookDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
h.ac.logger.Error(fmt.Sprintf("Issue reading %v, with error: %v", path, err))
return nil
Expand All @@ -70,7 +72,7 @@ func (h *Hooks) Load() {
if filepath.Ext(path) != ".lua" {
return nil
}
hookFiles = append(hookFiles, filepath.Join(h.ac.RootPath, path))
hookFiles = append(hookFiles, filepath.Join(path))
return nil
})

Expand Down Expand Up @@ -132,15 +134,17 @@ func (h *Hooks) readHookFile(filename string, basepath string, logger Logger) *H
yamlLib.Preload(lState)
stringsLib.Preload(lState)
lState.PreloadModule("http", ghttp.NewHttpModule(&http.Client{}).Loader)
if err := lState.DoFile(filename); err != nil {
logger.Error(fmt.Sprintf("Failed to execute hook: %v, with error: %v\n", filename, err))
panic("")
}

if basepath == "." {
lState.SetGlobal("workingdir", lua.LString(""))
} else {
lState.SetGlobal("workingdir", lua.LString(basepath))
}

if err := lState.DoFile(filename); err != nil {
logger.Error(fmt.Sprintf("Failed to execute hook: %v, with error: %v\n", filename, err))
panic("")
}
forFile := lState.GetGlobal("ForFile")
forFileValue := forFile.String()
return &HookSource{
Expand All @@ -153,7 +157,9 @@ func (h *Hooks) readHookFile(filename string, basepath string, logger Logger) *H

func (h *Hooks) ProcessFile(file transformers.TransformedFile) (hookedFile HookedFile) {
hookedFile.TransformedFile = file

fileData, _ := os.ReadFile(file.TransformedFile)
hookedFile.content = fileData

hookInput := struct {
Name string `json:"name"`
Expand Down Expand Up @@ -240,6 +246,7 @@ func readHookDirError(err error, directory string, logger Logger) {
logger.Error(
fmt.Sprintf("Failed to read the hooks dir: %v, with error: %v\n", directory, err),
)
panic("")
}

func mergeMapWithCheck(maps ...any) (source map[string]interface{}) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/alvu/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func (l *Logger) Debug(msg string) {
return
}
cs := color.ColorString{}
cs.Gray(l.logPrefix).Reset(" ").Green("✔").Reset(" ").Green(msg)
cs.Gray(l.logPrefix).Reset(" ").Gray("-").Reset(" ").Gray(msg)
fmt.Println(cs.String())
}

Expand Down

0 comments on commit ce1457e

Please sign in to comment.