cleaning up code that runs hugo

pull/8/head
Stephen Searles 7 years ago
parent 5b25695954
commit 618574f160
  1. 33
      client.go
  2. 67
      hugo.go

@ -61,18 +61,21 @@ func (ch *CaddyHugo) renderDraft(es *editSession) error {
return fmt.Errorf("error starting hugo: %v", err)
}
renderer := HugoCmdRenderer{
TmpDir: es.tmpdir,
SrcDir: ch.Dir,
Filename: es.filename,
}
go func() {
ticker := time.NewTicker(WebsocketFileTicker)
idleTicks := 0
closeTicks := int(IdleWebsocketTimeout / WebsocketFileTicker)
defer func() {
err := hugoCmd.Process.Signal(os.Interrupt)
if err != nil {
fmt.Println("error signaling to hugo:", err)
}
err = hugoCmd.Wait()
err = renderer.Stop()
if err != nil {
fmt.Println("error waiting for hugo:", err)
fmt.Println("error stopping hugo:", err)
}
}()
@ -80,15 +83,21 @@ func (ch *CaddyHugo) renderDraft(es *editSession) error {
<-ticker.C
ch.mtx.Lock()
err := ioutil.WriteFile(es.filename, []byte(es.doc.Contents()), 0644)
if err != nil {
fmt.Println("error saving document contents:", err)
// render if there are connected clients OR if we haven't
// been idle for very long.
if es.clients > 0 || idleTicks < 2 {
err := renderer.Render(es.doc.Contents())
if err != nil {
fmt.Println("error saving document contents:", err)
}
}
// count up idle time and possibly close down
if es.clients == 0 {
idleTicks++
idleTime := time.Duration(idleTicks) * WebsocketFileTicker
if idleTime >= IdleWebsocketTimeout {
if idleTicks >= closeTicks {
idleTime := time.Duration(idleTicks) * WebsocketFileTicker
err := ch.Publish()
fmt.Printf("idle for %v, quitting\n", idleTime)
if err != nil {
@ -100,8 +109,6 @@ func (ch *CaddyHugo) renderDraft(es *editSession) error {
delete(ch.docs, es.filename)
ch.mtx.Unlock()
return
} else {
fmt.Println("idle for", idleTime)
}
} else {
idleTicks = 0

@ -0,0 +1,67 @@
package caddyhugo
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"sync"
)
type HugoInteractor interface {
Render(srcdir, workdir string) HugoRenderer
}
type HugoRenderer interface {
Start() error
Stop() error
}
type HugoCmdRenderer struct {
SrcDir string
TmpDir string
Filename string
cmd *exec.Cmd
mtx sync.Mutex
}
func (hcr *HugoCmdRenderer) Render(contents string) error {
err := ioutil.WriteFile(hcr.Filename, []byte(contents), 0644)
return err
}
func (hcr *HugoCmdRenderer) Start() error {
hcr.mtx.Lock()
defer hcr.mtx.Unlock()
hcr.cmd = exec.Command("hugo", "--watch", "-D", "-d", hcr.TmpDir)
hcr.cmd.Dir = hcr.TmpDir
err := hcr.cmd.Start()
if err != nil {
return fmt.Errorf("error starting hugo: %v", err)
}
return nil
}
func (hcr *HugoCmdRenderer) Stop() error {
hcr.mtx.Lock()
defer hcr.mtx.Unlock()
if hcr.cmd == nil {
return nil
}
err := hcr.cmd.Process.Signal(os.Interrupt)
if err != nil {
return err
}
err = hcr.cmd.Wait()
if err != nil {
return err
}
return nil
}
Loading…
Cancel
Save