Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
iagapie committed Jul 4, 2023
0 parents commit e64e10c
Show file tree
Hide file tree
Showing 22 changed files with 1,593 additions and 0 deletions.
62 changes: 62 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
name: Tests

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
lint:
name: Golang-CI (lint)
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v4 # action page: <https://github.com/actions/setup-go>
with:
go-version: stable

- name: Run linter
uses: golangci/[email protected]
with:
version: v1.53
args: -v --build-tags=race --timeout=5m

test:
needs: lint
name: Unit tests
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v4 # action page: <https://github.com/actions/setup-go>
with:
go-version: stable

- name: Check out code
uses: actions/checkout@v3
with:
ref: ${{ github.ref }}

- name: Init Go modules Cache # Docs: <https://git.io/JfAKn#go---modules>
uses: actions/cache@v3
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-

- name: Install Go dependencies
run: go mod download

- name: Run Unit tests
run: go test -race -covermode=atomic -coverprofile /tmp/coverage.txt .

- name: Upload Coverage report to CodeCov
continue-on-error: true
uses: codecov/[email protected] # https://github.com/codecov/codecov-action
with:
file: /tmp/coverage.txt
25 changes: 25 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

# Go workspace file
go.work

**/.DS_Store
**/._.DS_Store
**/.idea
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 (GO) Wool

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Extends HTML Template

[![Build Status](https://github.com/gowool/extends-template/workflows/Tests/badge.svg?branch=main)](https://github.com/gowool/extends-template/actions?query=branch%3Amain)
[![codecov](https://codecov.io/gh/gowool/extends-template/branch/main/graph/badge.svg)](https://codecov.io/gh/gowool/extends-template)
[![License](https://img.shields.io/dub/l/vibe-d.svg)](https://github.com/gowool/extends-template/blob/main/LICENSE)

## Installation

```sh
go get github.com/gowool/extends-template
```

## License

Distributed under MIT License, please see license file within the code for more details.
59 changes: 59 additions & 0 deletions common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package et

import (
"crypto/sha256"
"fmt"
"reflect"
"regexp"
"unsafe"
)

const (
extendsPattern = `^%s\s*extends\s*"(.*?)"\s*%s`
templatePattern = `%s\s*template\s*"(.*?)".*?%s`
)

func ReExtends(left, right string) *regexp.Regexp {
return regexp.MustCompile(fmt.Sprintf(extendsPattern, left, right))
}

func ReTemplate(left, right string) *regexp.Regexp {
return regexp.MustCompile(fmt.Sprintf(templatePattern, left, right))
}

func merge(left error, right error) error {
switch {
case left == nil:
return right
case right == nil:
return left
}

return fmt.Errorf("%w; %w", left, right)
}

func errorf(right error, format string, a ...any) error {
return merge(fmt.Errorf(format, a...), right)
}

func typeName(i any) string {
t := reflect.TypeOf(i)

for t.Kind() == reflect.Ptr {
t = t.Elem()
}

return t.Name()
}

func toBytes(s string) []byte {
return unsafe.Slice(unsafe.StringData(s), len(s))
}

func toString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

func hash(data []byte) string {
return fmt.Sprintf("%x", sha256.Sum256(data))
}
145 changes: 145 additions & 0 deletions environment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package et

import (
"bytes"
"context"
"fmt"
"html/template"
"regexp"
"strconv"
"sync"
"sync/atomic"
)

const (
leftDelim = "{{"
rightDelim = "}}"
)

type Environment struct {
debug bool
global []string
left string
right string
loader Loader
reExtends *regexp.Regexp
reTemplates *regexp.Regexp
templates *sync.Map
funcMap template.FuncMap
hash atomic.Value
mu sync.Mutex
}

func NewEnvironment(loader Loader) *Environment {
e := &Environment{loader: loader}

return e.Delims(leftDelim, rightDelim)
}

func (e *Environment) Debug(debug bool) *Environment {
e.mu.Lock()
defer e.mu.Unlock()

if e.debug != debug {
e.debug = debug
e.updateHash()
}

return e
}

func (e *Environment) Delims(left, right string) *Environment {
e.mu.Lock()
defer e.mu.Unlock()

e.left = left
e.right = right
e.reExtends = ReExtends(left, right)
e.reTemplates = ReTemplate(left, right)
e.updateHash()

return e
}

func (e *Environment) Funcs(funcMap template.FuncMap) *Environment {
e.mu.Lock()
defer e.mu.Unlock()

e.funcMap = template.FuncMap{}
for k, v := range funcMap {
e.funcMap[k] = v
}
e.updateHash()

return e
}

func (e *Environment) Global(global ...string) *Environment {
e.mu.Lock()
defer e.mu.Unlock()

e.global = append(make([]string, 0, len(global)), global...)
e.updateHash()

return e
}

func (e *Environment) NewHTMLTemplate(name string) *template.Template {
return template.New(name).Delims(e.left, e.right).Funcs(e.funcMap)
}

func (e *Environment) NewTemplateWrapper(name string) *TemplateWrapper {
return NewTemplateWrapper(
e.NewHTMLTemplate(name),
e.loader,
e.reExtends,
e.reTemplates,
e.global...,
)
}

func (e *Environment) Load(ctx context.Context, name string) (*TemplateWrapper, error) {
e.mu.Lock()
defer e.mu.Unlock()

var wrapper *TemplateWrapper

key := e.key(name)

v, ok := e.templates.Load(key)
if ok {
wrapper = v.(*TemplateWrapper)
} else {
wrapper = e.NewTemplateWrapper(name)

e.templates.Store(key, wrapper)
}

if !ok || e.debug || !wrapper.IsFresh(ctx) {
if err := wrapper.Parse(ctx); err != nil {
return nil, err
}
}
return wrapper, nil
}

func (e *Environment) updateHash() {
var buf bytes.Buffer

buf.WriteString(e.left)
buf.WriteString(e.right)
buf.WriteString(strconv.FormatBool(e.debug))
for _, s := range e.global {
buf.WriteString(s)
}
for name, _ := range e.funcMap {

Check failure on line 135 in environment.go

View workflow job for this annotation

GitHub Actions / Golang-CI (lint)

S1005: unnecessary assignment to the blank identifier (gosimple)
buf.WriteString(name)
}

e.hash.Store(hash(buf.Bytes()))
e.templates = &sync.Map{}
}

func (e *Environment) key(name string) string {
return hash(toBytes(fmt.Sprintf("%s:%s", name, e.hash.Load())))
}
Loading

0 comments on commit e64e10c

Please sign in to comment.