filebrowser/editor.go
Henrique Dias c3c6c8f3d6 Return 0 when there is no error (Golang)
Former-commit-id: e7c4248761e085dd763c7d2fb93e3b364d46cc1f [formerly 59e9b4ed8b656dc61119e7c758fb47ee30c36ad6] [formerly 4e5e9413d14ec8ee0a3a2abbee7f607b15910315 [formerly b214fdd0ebe2bb564cbe64a12dbac725bc4d3f66]]
Former-commit-id: 1dc992ecd0b0169e66f854083554ae825ffa3ddf [formerly 65f85346c9875abcaaa0fa97fa8689ebea774f37]
Former-commit-id: aac3de2cf26430814b9db7073b42f5791ff2a566
2017-06-28 19:06:08 +01:00

121 lines
2.6 KiB
Go

package filemanager
import (
"bytes"
"errors"
"net/http"
"path/filepath"
"strings"
"github.com/hacdias/filemanager/frontmatter"
"github.com/spf13/hugo/parser"
)
// editor contains the information to fill the editor template.
type editor struct {
Class string `json:"class"`
Mode string `json:"mode"`
Visual bool `json:"visual"`
Content string `json:"content"`
FrontMatter struct {
Content *frontmatter.Content
Rune rune
} `json:"frontmatter"`
}
// getEditor gets the editor based on a Info struct
func getEditor(r *http.Request, i *fileInfo) (*editor, error) {
var err error
// Create a new editor variable and set the mode
e := &editor{}
e.Mode = editorMode(i.Name)
e.Class = editorClass(e.Mode)
if e.Class == "frontmatter-only" || e.Class == "complete" {
e.Visual = true
}
if r.URL.Query().Get("visual") == "false" {
e.Class = "content-only"
}
hasRune := frontmatter.HasRune(i.content)
if e.Class == "frontmatter-only" && !hasRune {
e.FrontMatter.Rune, err = frontmatter.StringFormatToRune(e.Mode)
if err != nil {
goto Error
}
i.content = frontmatter.AppendRune(i.content, e.FrontMatter.Rune)
hasRune = true
}
if e.Class == "frontmatter-only" && hasRune {
e.FrontMatter.Content, _, err = frontmatter.Pretty(i.content)
if err != nil {
goto Error
}
}
if e.Class == "complete" && hasRune {
var page parser.Page
// Starts a new buffer and parses the file using Hugo's functions
buffer := bytes.NewBuffer(i.content)
page, err = parser.ReadFrom(buffer)
if err != nil {
goto Error
}
// Parses the page content and the frontmatter
e.Content = strings.TrimSpace(string(page.Content()))
e.FrontMatter.Rune = rune(i.content[0])
e.FrontMatter.Content, _, err = frontmatter.Pretty(page.FrontMatter())
}
if e.Class == "complete" && !hasRune {
err = errors.New("Complete but without rune")
}
Error:
if e.Class == "content-only" || err != nil {
e.Class = "content-only"
e.Content = i.StringifyContent()
}
return e, nil
}
func editorClass(mode string) string {
switch mode {
case "json", "toml", "yaml":
return "frontmatter-only"
case "markdown", "asciidoc", "rst":
return "complete"
}
return "content-only"
}
func editorMode(filename string) string {
mode := strings.TrimPrefix(filepath.Ext(filename), ".")
switch mode {
case "md", "markdown", "mdown", "mmark":
mode = "markdown"
case "asciidoc", "adoc", "ad":
mode = "asciidoc"
case "rst":
mode = "rst"
case "html", "htm":
mode = "html"
case "js":
mode = "javascript"
case "go":
mode = "golang"
}
return mode
}