Skip to content

Commit

Permalink
feat: _layout.html
Browse files Browse the repository at this point in the history
add _layout.html as the basic way to define global  layout.

also deprecated _head and _tail file usage
  • Loading branch information
barelyhuman committed Apr 2, 2023
1 parent 6528f44 commit 58578f0
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 48 deletions.
2 changes: 1 addition & 1 deletion docs/hooks/01-add-navigation.lua
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function Writer(filedata)
local files = alvu.files(pagesPath)

for fileIndex = 1, #files do
if not (files[fileIndex] == "_head.html" or files[fileIndex] == "index.md" or files[fileIndex] == "_tail.html")
if not (files[fileIndex] == "_layout.html" or files[fileIndex] == "index.md")
then
local name = string.gsub(files[fileIndex], ".md", "")
name = string.gsub(name, ".html", "")
Expand Down
17 changes: 0 additions & 17 deletions docs/pages/_head.html

This file was deleted.

24 changes: 24 additions & 0 deletions docs/pages/_layout.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>alvu | documentation</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap"
rel="stylesheet" />
<link rel="stylesheet" href="{{.Meta.BaseURL}}styles.css">
</head>

<body>
{{.Content}}
<footer class="container">
Built with <a href="http://github.com/barelyhuman/alvu">alvu</a>
</footer>
</body>

</html>
5 changes: 0 additions & 5 deletions docs/pages/_tail.html

This file was deleted.

2 changes: 1 addition & 1 deletion docs/pages/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ rather tight flow made me think this'd work well.
As always, a tiny little tool built for me and hopefully someday someone else
might like it.

Well, let's head to [the basics &rarr;](01-the-basics)
Well, let's head to [the basics &rarr;]({{.Meta.BaseURL}}01-basics)
115 changes: 91 additions & 24 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,23 @@ var outPath string
var hardWraps bool
var hookCollection HookCollection

var reservedFiles []string = []string{"_head.html", "_tail.html", "_layout.html"}

type SiteMeta struct {
BaseURL string
}

type PageRenderData struct {
Meta SiteMeta
Data map[string]interface{}
Extras map[string]interface{}
}

type LayoutRenderData struct {
PageRenderData
Content template.HTML
}

func main() {
onDebug(func() {
debugInfo("Before Exec")
Expand All @@ -79,11 +92,15 @@ func main() {
pagesPath := path.Join(*basePathFlag, "pages")
publicPath := path.Join(*basePathFlag, "public")
headFilePath := path.Join(pagesPath, "_head.html")
baseFilePath := path.Join(pagesPath, "_layout.html")
tailFilePath := path.Join(pagesPath, "_tail.html")
outPath = path.Join(*outPathFlag)
hooksPath := path.Join(*basePathFlag, *hooksPathFlag)
hardWraps = *hardWrapsFlag

headTailDeprecationWarning := color.ColorString{}
headTailDeprecationWarning.Yellow(logPrefix).Yellow("[WARN] use of _tail.html and _head.html is deprecated, please use _layout.html instead")

onDebug(func() {
debugInfo("Opening _head")
memuse()
Expand All @@ -93,6 +110,19 @@ func main() {
if err == fs.ErrNotExist {
log.Println("no _head.html found,skipping")
}
} else {
fmt.Println(headTailDeprecationWarning.String())
}

onDebug(func() {
debugInfo("Opening _layout")
memuse()
})
baseFileFd, err := os.Open(baseFilePath)
if err != nil {
if err == fs.ErrNotExist {
log.Println("no _layout.html found,skipping")
}
}

onDebug(func() {
Expand All @@ -104,6 +134,8 @@ func main() {
if err == fs.ErrNotExist {
log.Println("no _tail.html found, skipping")
}
} else {
fmt.Println(headTailDeprecationWarning.String())
}

onDebug(func() {
Expand Down Expand Up @@ -154,14 +186,15 @@ func main() {
destFilePath := strings.Replace(toProcessItem, pagesPath, outPath, 1)

alvuFile := &AlvuFile{
lock: &sync.Mutex{},
sourcePath: toProcessItem,
destPath: destFilePath,
name: fileName,
headFile: headFileFd,
tailFile: tailFileFd,
data: map[string]interface{}{},
extras: map[string]interface{}{},
lock: &sync.Mutex{},
sourcePath: toProcessItem,
destPath: destFilePath,
name: fileName,
headFile: headFileFd,
tailFile: tailFileFd,
baseTemplate: baseFileFd,
data: map[string]interface{}{},
extras: map[string]interface{}{},
}

bail(alvuFile.ReadFile())
Expand Down Expand Up @@ -241,7 +274,7 @@ func CollectFilesToProcess(basepath string) []string {
for _, pathInfo := range pathstoprocess {
_path := path.Join(basepath, pathInfo.Name())

if pathInfo.Name() == "_head.html" || pathInfo.Name() == "_tail.html" {
if Contains(reservedFiles, pathInfo.Name()) {
continue
}

Expand All @@ -250,6 +283,7 @@ func CollectFilesToProcess(basepath string) []string {
} else {
files = append(files, _path)
}

}

return files
Expand Down Expand Up @@ -284,7 +318,8 @@ func CollectHooks(basePath, hooksBasePath string) {
func initMDProcessor(highlight bool, theme string) {

rendererOptions := []renderer.Option{
html.WithXHTML(), html.WithUnsafe(),
html.WithXHTML(),
html.WithUnsafe(),
}

if hardWraps {
Expand Down Expand Up @@ -352,6 +387,7 @@ type AlvuFile struct {
writeableContent []byte
headFile *os.File
tailFile *os.File
baseTemplate *os.File
targetName []byte
data map[string]interface{}
extras map[string]interface{}
Expand Down Expand Up @@ -482,42 +518,57 @@ func (a *AlvuFile) FlushFile() {

writeHeadTail := false

if filepath.Ext(a.sourcePath) == ".md" || filepath.Ext(a.sourcePath) == "html" {
if a.baseTemplate == nil && (filepath.Ext(a.sourcePath) == ".md" || filepath.Ext(a.sourcePath) == "html") {
writeHeadTail = true
}

if writeHeadTail && a.headFile != nil {
shouldCopyContentsWithReset(a.headFile, f)
}

renderData := struct {
Meta SiteMeta
Data map[string]interface{}
Extras map[string]interface{}
}{
renderData := PageRenderData{
Meta: SiteMeta{
BaseURL: baseurl,
},
Data: a.data,
Extras: a.extras,
}

var preMarkdown bytes.Buffer
preTemplate := template.New("temporary_pre_template")
preTemplate.Parse(string(a.writeableContent))
err = preTemplate.Execute(&preMarkdown, renderData)
// Run the Markdown file through the conversion
// process to be able to use template variables in
// the markdown instead of writing them in
// raw HTML
var preConvertHTML bytes.Buffer
preConvertTmpl := template.New("temporary_pre_template")
preConvertTmpl.Parse(string(a.writeableContent))
err = preConvertTmpl.Execute(&preConvertHTML, renderData)
bail(err)

var toHtml bytes.Buffer

err = mdProcessor.Convert(preMarkdown.Bytes(), &toHtml)
err = mdProcessor.Convert(preConvertHTML.Bytes(), &toHtml)
bail(err)

layoutData := LayoutRenderData{
PageRenderData: renderData,
Content: template.HTML(toHtml.Bytes()),
}

// If a layout file was found
// write the converted html content into the
// layout template file
if a.baseTemplate != nil {
layout := template.New("layout")
layoutTemplateData := string(readFileToBytes(a.baseTemplate))
toHtml.Reset()
layout.Parse(layoutTemplateData)
layout.Execute(&toHtml, layoutData)
}

io.Copy(
f, &toHtml,
)

if writeHeadTail && a.tailFile != nil {
if writeHeadTail && a.tailFile != nil && a.baseTemplate == nil {
shouldCopyContentsWithReset(a.tailFile, f)
}

Expand Down Expand Up @@ -553,7 +604,6 @@ func NewHook() *lua.LState {
}

// UTILS

func memuse() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
Expand Down Expand Up @@ -605,6 +655,14 @@ func mergeMapWithCheck(maps ...any) (source map[string]interface{}) {
return source
}

func readFileToBytes(fd *os.File) []byte {
buf := &bytes.Buffer{}
fd.Seek(0, 0)
_, err := io.Copy(buf, fd)
bail(err)
return buf.Bytes()
}

func shouldCopyContentsWithReset(src *os.File, target *os.File) {
src.Seek(0, 0)
_, err := io.Copy(target, src)
Expand Down Expand Up @@ -672,3 +730,12 @@ func notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404, Page not found....")
}

func Contains(collection []string, item string) bool {
for _, x := range collection {
if item == x {
return true
}
}
return false
}

0 comments on commit 58578f0

Please sign in to comment.