filebrowser/handlers/editor.go

90 lines
2.1 KiB
Go
Raw Normal View History

2016-10-22 11:07:19 +00:00
package handlers
2016-06-23 22:21:44 +00:00
import (
"bytes"
"path/filepath"
"strings"
2016-10-22 11:07:19 +00:00
"github.com/hacdias/caddy-filemanager/file"
2016-06-28 09:24:02 +00:00
"github.com/hacdias/caddy-filemanager/frontmatter"
2016-06-23 22:21:44 +00:00
"github.com/spf13/hugo/parser"
)
// Editor contains the information for the editor page
type Editor struct {
Class string
Mode string
Content string
2016-06-28 09:24:02 +00:00
FrontMatter *frontmatter.Content
2016-06-23 22:21:44 +00:00
}
// GetEditor gets the editor based on a FileInfo struct
2016-10-22 11:07:19 +00:00
func GetEditor(i *file.Info) (*Editor, error) {
2016-06-23 22:21:44 +00:00
// Create a new editor variable and set the mode
editor := new(Editor)
2017-01-03 15:10:33 +00:00
editor.Mode = strings.TrimPrefix(filepath.Ext(i.Name), ".")
2016-06-23 22:21:44 +00:00
switch editor.Mode {
case "md", "markdown", "mdown", "mmark":
editor.Mode = "markdown"
case "asciidoc", "adoc", "ad":
editor.Mode = "asciidoc"
case "rst":
editor.Mode = "rst"
case "html", "htm":
editor.Mode = "html"
case "js":
editor.Mode = "javascript"
2016-11-01 15:12:26 +00:00
case "go":
editor.Mode = "golang"
2016-06-23 22:21:44 +00:00
}
var page parser.Page
var err error
// Handle the content depending on the file extension
switch editor.Mode {
case "json", "toml", "yaml":
// Defines the class and declares an error
editor.Class = "frontmatter-only"
// Checks if the file already has the frontmatter rune and parses it
2016-10-18 20:49:46 +00:00
if frontmatter.HasRune(i.Content) {
2016-10-18 20:06:31 +00:00
editor.FrontMatter, _, err = frontmatter.Pretty(i.Content)
2016-06-23 22:21:44 +00:00
} else {
2016-10-18 20:49:46 +00:00
editor.FrontMatter, _, err = frontmatter.Pretty(frontmatter.AppendRune(i.Content, editor.Mode))
2016-06-23 22:21:44 +00:00
}
// Check if there were any errors
2016-10-18 20:49:46 +00:00
if err == nil {
2016-10-18 16:56:35 +00:00
break
2016-06-23 22:21:44 +00:00
}
2016-10-18 20:49:46 +00:00
fallthrough
case "markdown", "asciidoc", "rst":
if frontmatter.HasRune(i.Content) {
// Starts a new buffer and parses the file using Hugo's functions
buffer := bytes.NewBuffer(i.Content)
page, err = parser.ReadFrom(buffer)
editor.Class = "complete"
if err == nil {
// Parses the page content and the frontmatter
editor.Content = strings.TrimSpace(string(page.Content()))
editor.FrontMatter, _, err = frontmatter.Pretty(page.FrontMatter())
2016-10-31 21:25:14 +00:00
if err == nil {
break
}
2016-10-18 20:49:46 +00:00
}
}
fallthrough
2016-06-23 22:21:44 +00:00
default:
editor.Class = "content-only"
2016-10-18 20:06:31 +00:00
editor.Content = i.StringifyContent()
2016-06-23 22:21:44 +00:00
}
2016-10-18 16:56:35 +00:00
2016-06-23 22:21:44 +00:00
return editor, nil
}