Browse Source

gofmt

master
juju2013 10 months ago
parent
commit
315d1b3e55
7 changed files with 165 additions and 165 deletions
  1. 1
    0
      .gitignore
  2. 145
    141
      gen.go
  3. 3
    4
      logger.go
  4. 1
    1
      rss.go
  5. 0
    1
      server.go
  6. 1
    1
      tpldata.go
  7. 14
    17
      watch.go

+ 1
- 0
.gitignore View File

@@ -5,3 +5,4 @@ public/
out/
tags
jfever
.realize.yaml

+ 145
- 141
gen.go View File

@@ -7,7 +7,7 @@ import (
"io/ioutil"
"os"
"path/filepath"
"regexp"
"regexp"
"strings"
"time"

@@ -16,42 +16,47 @@ import (

// Site data
type Site struct {
RootCMS *CMS // root CMS
Navigation string // navigation HTML
RootCMS *CMS // root CMS
Navigation string // navigation HTML
}

// Content Management Struct
type CMS struct {
path string // part of path relatif to SRC and OUT
name string // navigation name
outfiles []os.FileInfo // (extra) files in Out
srcfiles []os.FileInfo // Source files
subdirs []*CMS // subdirectories
path string // part of path relatif to SRC and OUT
name string // navigation name
outfiles []os.FileInfo // (extra) files in Out
srcfiles []os.FileInfo // Source files

// Navigation links
subdirs []*CMS // subdirectories
Previous *CMS
Next *CMS
Up *CMS
}

// return the full Out path
func (cms *CMS) GetOutDir() string {
return filepath.Join(PublicDir, cms.path)
return filepath.Join(PublicDir, cms.path)
}

// return the full Src path
func (cms *CMS) GetSrcDir() string {
return filepath.Join(PostsDir, cms.path)
return filepath.Join(PostsDir, cms.path)
}

var (
//postTpl *template.Template // The one and only compiled post template
postTpls map[string]*template.Template // [templateName]=*compiledTemplate
postTplNm = "post.amber" // The amber post template file name (native Go are compiled using ParseGlob)
site = Site{}
site = Site{}

funcs = template.FuncMap{
"fmttime": func(t time.Time, f string) string {
return t.Format(f)
},
"navmenu": func() string {
return NavigationMenu()
},
"navmenu": func() string {
return NavigationMenu()
},
}
)

@@ -75,163 +80,163 @@ func compileTemplates() (err error) {
if err != nil {
return
}
postTpls = tmptpl
postTpls = tmptpl
postTplNm = "post"
if _, exists = postTpls[postTplNm]; !exists {
return fmt.Errorf("error parsing templates: %v", err)
}
DEBUG("Directory compiled: %v", TemplatesDir)
DEBUG("Directory compiled: %v", TemplatesDir)
return nil
}

// scan a directory tree and generate outputs
func genPath(dir string) {
site.RootCMS = CMSTree(".")
site.BuildNavigation()
site.RootCMS.BuildTree()
site.RootCMS = CMSTree(".")
site.BuildNavigation()
site.RootCMS.BuildTree()
}

// Build a CMS tree from SRC directory tree
func CMSTree(dir string) *CMS {
cms := CMS{path: dir, name: filepath.Base(dir)}
files, err := ioutil.ReadDir(cms.GetSrcDir())
if err != nil {
WARN(err.Error())
return nil
}
// walk all files first
for _, fi := range files {
if fi.IsDir() {
if subcms := CMSTree(filepath.Join(cms.path, fi.Name())); subcms != nil {
cms.subdirs = append(cms.subdirs, subcms)
}
} else {
cms.srcfiles = append(cms.srcfiles, fi)
}
}
return &cms
cms := CMS{path: dir, name: filepath.Base(dir)}
files, err := ioutil.ReadDir(cms.GetSrcDir())
if err != nil {
WARN(err.Error())
return nil
}
// walk all files first
for _, fi := range files {
if fi.IsDir() {
if subcms := CMSTree(filepath.Join(cms.path, fi.Name())); subcms != nil {
cms.subdirs = append(cms.subdirs, subcms)
}
} else {
cms.srcfiles = append(cms.srcfiles, fi)
}
}
return &cms
}

// from template
func NavigationMenu() string {
site.BuildNavigation()
return site.Navigation
site.BuildNavigation()
return site.Navigation
}

// Build a simple navigation tree with ul/li
func (site *Site) BuildNavigation() {
var f func(*CMS) string
f = func(cms *CMS) string {
html:=""
for _, scms := range cms.subdirs {
html+=" <li>"+scms.name+"</li> "
html+=f(scms)
}
if len(html)>0 {
html=" <ul>"+html+"</ul> "
}
return html
}
site.Navigation = f(site.RootCMS)
var f func(*CMS) string
f = func(cms *CMS) string {
html := ""
for _, scms := range cms.subdirs {
html += " <li>" + scms.name + "</li> "
html += f(scms)
}
if len(html) > 0 {
html = " <ul>" + html + "</ul> "
}
return html
}
site.Navigation = f(site.RootCMS)
}

// Build the site from CMS
func (cms *CMS) BuildTree() {
// build all pages for current directory
cms.PopulateOut()
for _, fi := range cms.srcfiles {
fname := fi.Name()
if strings.HasPrefix(fi.Name(), ".") {
continue
}
if matched, _ := regexp.MatchString(".*\\.md", fname); matched {
cms.generate(fname)
} else {
cms.copy(fname)
}
}
// build sub-directories
for _, fi := range cms.subdirs {
fi.BuildTree()
}
// clean up
cms.CleanOut()
// build all pages for current directory
cms.PopulateOut()
for _, fi := range cms.srcfiles {
fname := fi.Name()
if strings.HasPrefix(fi.Name(), ".") {
continue
}
if matched, _ := regexp.MatchString(".*\\.md", fname); matched {
cms.generate(fname)
} else {
cms.copy(fname)
}
}
// build sub-directories
for _, fi := range cms.subdirs {
fi.BuildTree()
}
// clean up
cms.CleanOut()
}

// Copy as is a Src file to an Out file
func (cms *CMS) copy(src string) {
fsrc := filepath.Join(cms.GetSrcDir(), src)
fdst := filepath.Join(cms.GetOutDir(), src)
inf, err := os.Open(fsrc)
if err != nil {
ERROR(err.Error())
return
}
defer inf.Close()
ouf, err := os.Create(fdst)
if err != nil {
ERROR(err.Error())
return
}
defer ouf.Close()
_, err = io.Copy(ouf, inf)
if err != nil {
ERROR(err.Error())
return
}
cms.legit(src)
fsrc := filepath.Join(cms.GetSrcDir(), src)
fdst := filepath.Join(cms.GetOutDir(), src)
inf, err := os.Open(fsrc)
if err != nil {
ERROR(err.Error())
return
}
defer inf.Close()
ouf, err := os.Create(fdst)
if err != nil {
ERROR(err.Error())
return
}
defer ouf.Close()
_, err = io.Copy(ouf, inf)
if err != nil {
ERROR(err.Error())
return
}
cms.legit(src)
}

// Mark a file in Out as legit from Src, by deleting it from outfiles
func (cms *CMS) legit(src string) {
nf := []os.FileInfo{}
for _, f := range cms.outfiles {
if f.Name() != src {
nf = append(nf, f)
}
}
cms.outfiles = nf
nf := []os.FileInfo{}
for _, f := range cms.outfiles {
if f.Name() != src {
nf = append(nf, f)
}
}
cms.outfiles = nf
}

// Cleanup: delete any extra files in Pub not present in Post
func (cms *CMS) CleanOut() {
for _, f := range cms.outfiles {
os.Remove(filepath.Join(cms.GetOutDir(), f.Name()))
}
cms.path = ""
cms.outfiles = nil
for _, f := range cms.outfiles {
os.Remove(filepath.Join(cms.GetOutDir(), f.Name()))
}
cms.path = ""
cms.outfiles = nil
}
// Populate pubContent from a PostsDir's sub dir
func (cms *CMS) PopulateOut() {
outDir := cms.GetOutDir()
os.MkdirAll(outDir, 0755)
files, err := ioutil.ReadDir(outDir)
if err != nil {
WARN(err.Error())
return
}
for _, f := range files {
if ! f.IsDir() {
cms.outfiles = append(cms.outfiles, f)
}
}
outDir := cms.GetOutDir()
os.MkdirAll(outDir, 0755)
files, err := ioutil.ReadDir(outDir)
if err != nil {
WARN(err.Error())
return
}
for _, f := range files {
if !f.IsDir() {
cms.outfiles = append(cms.outfiles, f)
}
}
}

// Clear the public directory, ignoring special files, subdirectories, and hidden (dot) files.
func clearPublicDir() error {
// do nothing for now
return nil
// do nothing for now
return nil
// Clear the public directory, except subdirs and special files (favicon.ico & co.)
fis, err := ioutil.ReadDir(PublicDir)
if err != nil {
@@ -272,11 +277,11 @@ func getPosts(fis []os.FileInfo) (all, recent []*PostData) {
func generateSite() error {
// First compile the template(s)
if err := compileTemplates(); err != nil {
DEBUG("template error")
DEBUG("template error")
return err
}
genPath(PostsDir)
return nil
genPath(PostsDir)
return nil
}

/*
@@ -305,34 +310,33 @@ func generateRss(td []*PostData) error {
*/

func (cms *CMS) generate(mdf string) {
if data, err := cms.genContent(mdf); err == nil {
cms.generateFile(data, false)
}
if data, err := cms.genContent(mdf); err == nil {
cms.generateFile(data, false)
}
}


// Generate the static HTML file for the post identified by the index.
func (cms *CMS) generateFile(td *PostData, idx bool) {
var w io.Writer

// check if template exists
tplName, ok := td.D["Template"]
if ! ok {
tplName="default"
}
if !ok {
tplName = "default"
}
var tpl *template.Template
var ex bool

if tpl, ex = postTpls[tplName]; !ex {
ERROR("Template not found: %s", tplName)
return
return
}

slug := td.D["Slug"]
fw, err := os.Create(filepath.Join(cms.GetOutDir(), slug))
if err != nil {
ERROR("error creating static file %s: %s", slug, err)
return
return
}
defer fw.Close()

@@ -342,11 +346,11 @@ func (cms *CMS) generateFile(td *PostData, idx bool) {
idxw, err := os.Create(filepath.Join(cms.GetOutDir(), "index.html"))
if err != nil {
ERROR("error creating static file index.html: %s", err)
return
return
}
defer idxw.Close()
w = io.MultiWriter(fw, idxw)
}
tpl.ExecuteTemplate(w, tplName+".amber", td)
cms.legit(slug)
cms.legit(slug)
}

+ 3
- 4
logger.go View File

@@ -3,14 +3,13 @@ package main
import (
"log"
"os"
"runtime/debug"
"runtime/debug"
)

func INFO(format string, args ...interface{}) {
log.Printf("[INFO]"+format, args...)
}


func WARN(format string, args ...interface{}) {
if Options.Debug {
log.Printf("[WARN]"+format, args...)
@@ -24,13 +23,13 @@ func DEBUG(format string, args ...interface{}) {
}

func ERROR(format string, args ...interface{}) {
debug.PrintStack()
debug.PrintStack()
log.Printf("[ERROR]"+format, args...)
}

func FATAL(format string, args ...interface{}) {
log.Printf("[FATAL]"+format, args...)
debug.PrintStack()
debug.PrintStack()
os.Exit(1)
}


+ 1
- 1
rss.go View File

@@ -57,7 +57,7 @@ type Item struct {
func NewRss(title string, description string, link string) *Rss {
rss := &Rss{Version: "2.0",
Channels: []*Channel{
&Channel{
{
Title: title,
Description: description,
Link: link,

+ 0
- 1
server.go View File

@@ -37,4 +37,3 @@ func run() {
FATAL(err.Error())
}
}


+ 1
- 1
tpldata.go View File

@@ -148,7 +148,7 @@ func (cms *CMS) genContent(mdf string) (*PostData, error) {
}

slug := getSlug(mdf)
fi, _ := f.Stat()
fi, _ := f.Stat()
pubdt := fi.ModTime()
if dt, ok := td["Date"]; ok && len(dt) > 0 {
pubdt, err = time.Parse(pubDtFmt[len(dt)], dt)

+ 14
- 17
watch.go View File

@@ -15,8 +15,7 @@ const (

var (
fwatcher *watcher.Watcher

tempo = make(chan time.Time, 100)
generate = make(chan bool, 1)
)
@@ -26,36 +25,35 @@ func beginWatch(paths ...string) {
fwatcher = watcher.New()
fwatcher.SetMaxEvents(1)
fwatcher.FilterOps(watcher.Rename, watcher.Move, watcher.Create, watcher.Remove, watcher.Write)
fwatcher.IgnoreHiddenFiles(true)
fwatcher.Ignore("examples")
fwatcher.IgnoreHiddenFiles(true)
fwatcher.Ignore("examples")
go fwHandler()

// Start by rebuild - and launch - your program
rebuild()

// The root directory for source to watch
for _, path := range paths {
if err := fwatcher.AddRecursive(path); err != nil {
ERROR(err.Error())
}
}
for _, path := range paths {
if err := fwatcher.AddRecursive(path); err != nil {
ERROR(err.Error())
}
}

// start watch source change, will loop
DEBUG("Begin file watch")
DEBUG("Begin file watch")
if err := fwatcher.Start(watchEventDelay); err != nil {
FATAL(err.Error())
}
}


// Handle watch events such as file change, error or exit
func fwHandler() {
for {
select {
case event := <-fwatcher.Event:
DEBUG("Change :%v", event) // Print the event's info.
go rebuild()
DEBUG("Change :%v", event) // Print the event's info.
go rebuild()
case err := <-fwatcher.Error:
WARN(err.Error())
case <-fwatcher.Closed:
@@ -65,7 +63,6 @@ func fwHandler() {
}

func rebuild() {
DEBUG("REBUILD...")
generateSite()
DEBUG("REBUILD...")
generateSite()
}


Loading…
Cancel
Save