package caddyhugo import ( "encoding/base64" "fmt" "io/ioutil" "net/http" "os" "path" "sync" "git.stephensearles.com/stephen/acedoc" "git.stephensearles.com/stephen/idleshut" ) type editSession struct { clients uint docname string filename string doc *acedoc.Document tmpdir string mtx sync.Mutex } func (es *editSession) Clients() uint { es.mtx.Lock() defer es.mtx.Unlock() return es.clients } func (ch *CaddyHugo) newEditSession(docName string) (*editSession, error) { filename := ch.docFilename(docName) fmt.Println("opening", filename) contents, err := ioutil.ReadFile(filename) if err != nil { return nil, err } draftPrefix := fmt.Sprintf("draft-%s", base64.RawURLEncoding.EncodeToString([]byte(docName))) tmpdir := path.Join(os.TempDir(), draftPrefix) es := &editSession{ docname: docName, filename: filename, doc: acedoc.NewString(string(contents)), tmpdir: tmpdir, } err = es.doc.LogToFile(path.Join(ch.Dir, "logs", docName)) if err != nil { fmt.Println(err) return nil, err } ch.docs[filename] = es ch.renderDraft(es) return es, nil } func (ch *CaddyHugo) renderDraft(es *editSession) error { var proc *idleshut.Process f := func() { if es.clients != 0 { proc.Touch() } } proc = idleshut.New(HugoCmdProcessConfig(ch, es, f)) return nil } func (ch *CaddyHugo) hasEditSession(docName string) (*editSession, bool) { dr, ok := ch.docs[ch.docFilename(docName)] return dr, ok } func (ch *CaddyHugo) editSession(docName string) (*editSession, error) { ch.mtx.Lock() defer ch.mtx.Unlock() var err error dr, ok := ch.hasEditSession(docName) if !ok { dr, err = ch.newEditSession(docName) } return dr, err } func docNameFromEditRequest(r *http.Request) string { return r.URL.Path[len("/hugo/edit/"):] }