You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
caddy-hugo2/client.go

114 lines
2.3 KiB

package caddyhugo
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
"git.stephensearles.com/stephen/acedoc"
)
type docref struct {
clients uint
name string
doc *acedoc.Document
tmpdir string
}
func (ch *CaddyHugo) doc(r *http.Request) (*docref, error) {
ch.mtx.Lock()
defer ch.mtx.Unlock()
name := r.URL.Path[len("/hugo/edit/"):]
name = filepath.Join(ch.Dir, name)
name = strings.ToLower(name)
_, ok := ch.docs[ch.docname(name)]
if !ok {
fmt.Println("opening", name)
contents, err := ioutil.ReadFile(name)
if err != nil {
return nil, err
}
draftPrefix := fmt.Sprintf("draft-%s", base64.RawURLEncoding.EncodeToString([]byte(name)))
tmpdir := path.Join(os.TempDir(), draftPrefix)
ref := &docref{
name: name,
doc: acedoc.NewString(string(contents)),
tmpdir: tmpdir,
}
err = ref.doc.LogToFile(path.Join(ch.Dir, "logs", r.URL.Path[len("/hugo/edit/"):]))
if err != nil {
fmt.Println(err)
return nil, err
}
ch.docs[ch.docname(name)] = ref
hugoCmd := exec.Command("hugo", "--watch", "-D", "-d", ref.tmpdir)
hugoCmd.Dir = ch.Dir
err = hugoCmd.Start()
if err != nil {
return nil, fmt.Errorf("error starting hugo: %v", err)
}
go func() {
ticker := time.NewTicker(WebsocketFileTicker)
idleTicks := 0
defer func() {
err := hugoCmd.Process.Signal(os.Interrupt)
if err != nil {
fmt.Println("error signaling to hugo:", err)
}
err = hugoCmd.Wait()
if err != nil {
fmt.Println("error waiting for hugo:", err)
}
}()
for {
<-ticker.C
ch.mtx.Lock()
err := ioutil.WriteFile(name, []byte(ref.doc.Contents()), 0644)
if err != nil {
fmt.Println("error saving document contents:", err)
}
if ref.clients == 0 {
idleTicks++
idleTime := time.Duration(idleTicks) * WebsocketFileTicker
if idleTime >= IdleWebsocketTimeout {
err := ch.Publish()
fmt.Printf("idle for %v, quitting\n", idleTime)
if err != nil {
fmt.Printf(", error publishing: %v\n", err)
}
ref.doc.Close()
os.RemoveAll(tmpdir)
delete(ch.docs, ch.docname(name))
ch.mtx.Unlock()
return
}
} else {
idleTicks = 0
}
ch.mtx.Unlock()
}
}()
}
return ch.docs[ch.docname(name)], nil
}