Extracting html templates into a library (#16946)
* Extracting html templates into a library * Moving tests to the right place * Fixing tests * Addressing PR review comments * Addressing PR review comments * Replacing attomic with RWMutex * Returning errors as channel for Templates watcher * Address PR review comments * Other small fixes * Simplifying NewWithWatcher * Addressing PR review comments * Making error handling on rendering templates more robust * Fixing tests * Changing how we return errors * Fixing shadow variables * Addressing PR review comments * Logging errors from the outside of sendNotificationEmail * Fixing lock in shutdown * Fixing the resource copy for commands tests temporary directories * Removing unused import * A couple of tiny fixes
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
58dce5930e
Коммит
95b0809850
118
utils/html.go
118
utils/html.go
@@ -1,118 +0,0 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"html/template"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/utils/fileutils"
|
||||
)
|
||||
|
||||
type HTMLTemplateWatcher struct {
|
||||
templates atomic.Value
|
||||
stop chan struct{}
|
||||
stopped chan struct{}
|
||||
}
|
||||
|
||||
func NewHTMLTemplateWatcher(directory string) (*HTMLTemplateWatcher, error) {
|
||||
templatesDir, _ := fileutils.FindDir(directory)
|
||||
mlog.Debug("Parsing server templates", mlog.String("templates_directory", templatesDir))
|
||||
|
||||
ret := &HTMLTemplateWatcher{
|
||||
stop: make(chan struct{}),
|
||||
stopped: make(chan struct{}),
|
||||
}
|
||||
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = watcher.Add(templatesDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
htmlTemplates, err := template.ParseGlob(filepath.Join(templatesDir, "*.html"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ret.templates.Store(htmlTemplates)
|
||||
|
||||
go func() {
|
||||
defer close(ret.stopped)
|
||||
defer watcher.Close()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ret.stop:
|
||||
return
|
||||
case event := <-watcher.Events:
|
||||
if event.Op&fsnotify.Write == fsnotify.Write {
|
||||
mlog.Info("Re-parsing templates because of modified file", mlog.String("file_name", event.Name))
|
||||
if htmlTemplates, err := template.ParseGlob(filepath.Join(templatesDir, "*.html")); err != nil {
|
||||
mlog.Error("Failed to parse templates.", mlog.Err(err))
|
||||
} else {
|
||||
ret.templates.Store(htmlTemplates)
|
||||
}
|
||||
}
|
||||
case err := <-watcher.Errors:
|
||||
mlog.Error("Failed in directory watcher", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (w *HTMLTemplateWatcher) Templates() *template.Template {
|
||||
return w.templates.Load().(*template.Template)
|
||||
}
|
||||
|
||||
func (w *HTMLTemplateWatcher) Close() {
|
||||
close(w.stop)
|
||||
<-w.stopped
|
||||
}
|
||||
|
||||
type HTMLTemplate struct {
|
||||
Templates *template.Template
|
||||
TemplateName string
|
||||
Props map[string]interface{}
|
||||
HTML map[string]template.HTML
|
||||
}
|
||||
|
||||
func NewHTMLTemplate(templates *template.Template, templateName string) *HTMLTemplate {
|
||||
return &HTMLTemplate{
|
||||
Templates: templates,
|
||||
TemplateName: templateName,
|
||||
Props: make(map[string]interface{}),
|
||||
HTML: make(map[string]template.HTML),
|
||||
}
|
||||
}
|
||||
|
||||
func (t *HTMLTemplate) Render() string {
|
||||
var text bytes.Buffer
|
||||
t.RenderToWriter(&text)
|
||||
return text.String()
|
||||
}
|
||||
|
||||
func (t *HTMLTemplate) RenderToWriter(w io.Writer) error {
|
||||
if t.Templates == nil {
|
||||
return errors.New("no html templates")
|
||||
}
|
||||
|
||||
if err := t.Templates.ExecuteTemplate(w, t.TemplateName, t); err != nil {
|
||||
mlog.Warn("Error rendering template", mlog.String("template_name", t.TemplateName), mlog.Err(err))
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"html/template"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestHTMLTemplateWatcher(t *testing.T) {
|
||||
TranslationsPreInit()
|
||||
|
||||
dir, err := ioutil.TempDir("", "")
|
||||
require.NoError(t, err)
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
require.NoError(t, os.Mkdir(filepath.Join(dir, "templates"), 0700))
|
||||
require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "templates", "foo.html"), []byte(`{{ define "foo" }}foo{{ end }}`), 0600))
|
||||
|
||||
prevDir, err := os.Getwd()
|
||||
require.NoError(t, err)
|
||||
defer os.Chdir(prevDir)
|
||||
os.Chdir(dir)
|
||||
|
||||
watcher, err := NewHTMLTemplateWatcher("templates")
|
||||
require.NotNil(t, watcher)
|
||||
require.NoError(t, err)
|
||||
defer watcher.Close()
|
||||
|
||||
tpl := NewHTMLTemplate(watcher.Templates(), "foo")
|
||||
assert.Equal(t, "foo", tpl.Render())
|
||||
|
||||
require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "templates", "foo.html"), []byte(`{{ define "foo" }}bar{{ end }}`), 0600))
|
||||
|
||||
for i := 0; i < 30; i++ {
|
||||
tpl = NewHTMLTemplate(watcher.Templates(), "foo")
|
||||
if tpl.Render() == "bar" {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond * 50)
|
||||
}
|
||||
assert.Equal(t, "bar", tpl.Render())
|
||||
}
|
||||
|
||||
func TestHTMLTemplateWatcher_BadDirectory(t *testing.T) {
|
||||
TranslationsPreInit()
|
||||
watcher, err := NewHTMLTemplateWatcher("notarealdirectory")
|
||||
assert.Nil(t, watcher)
|
||||
assert.Error(t, err)
|
||||
}
|
||||
|
||||
func TestHTMLTemplate(t *testing.T) {
|
||||
tpl := template.New("test")
|
||||
_, err := tpl.Parse(`{{ define "foo" }}foo{{ .Props.Bar }}{{ end }}`)
|
||||
require.NoError(t, err)
|
||||
|
||||
htmlTemplate := NewHTMLTemplate(tpl, "foo")
|
||||
htmlTemplate.Props["Bar"] = "bar"
|
||||
assert.Equal(t, "foobar", htmlTemplate.Render())
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
require.NoError(t, htmlTemplate.RenderToWriter(buf))
|
||||
assert.Equal(t, "foobar", buf.String())
|
||||
}
|
||||
|
||||
func TestHTMLTemplate_RenderError(t *testing.T) {
|
||||
tpl := template.New("test")
|
||||
_, err := tpl.Parse(`{{ define "foo" }}foo{{ .Foo.Bar }}bar{{ end }}`)
|
||||
require.NoError(t, err)
|
||||
|
||||
htmlTemplate := NewHTMLTemplate(tpl, "foo")
|
||||
assert.Equal(t, "foo", htmlTemplate.Render())
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
assert.Error(t, htmlTemplate.RenderToWriter(buf))
|
||||
assert.Equal(t, "foo", buf.String())
|
||||
}
|
||||
Ссылка в новой задаче
Block a user