Skip to content

Instantly share code, notes, and snippets.

@urielhdz
Created October 24, 2017 15:27
Show Gist options
  • Save urielhdz/bb4a285701aa3bdf70260ba53948d14d to your computer and use it in GitHub Desktop.
Save urielhdz/bb4a285701aa3bdf70260ba53948d14d to your computer and use it in GitHub Desktop.
Watches the files from a specified directory to automatically transform .ace files into html files, using a layout.ace file as base
package ace_builder
import(
"log"
"github.com/fsnotify/fsnotify"
"github.com/yosssi/ace"
"strings"
"bufio"
"os"
)
func check(e error){
if e != nil{
log.Fatal(e)
}
}
func fileNameWithoutExtension(filePath string) string{
filePathParts := strings.Split(filePath,"/")
return strings.Split(filePathParts[len(filePathParts)-1],".")[0]
}
func filePathWithouthExtension(filePath string) string{
return strings.Split(filePath,".")[0]
}
func workingDirectory(pathWithFilename string) string{
pathElements := strings.Split(pathWithFilename,"/")
return strings.Join(pathElements[:len(pathElements)-1],"/")
}
func layoutPath(pathWithFilename string) string{
return workingDirectory(pathWithFilename) + "/layout"
}
func Transform(filePath, buildDirectory string){
transform(filePath,buildDirectory)
}
func transform(filePath,buildDirectory string){
// data, err := ioutil.ReadFile(filePath)
// check(err)
options := ace.Options{DynamicReload: true}
tpl,err := ace.Load(layoutPath(filePath),filePathWithouthExtension(filePath),&options)
check(err)
scope := make(map[string]string)
fileName := fileNameWithoutExtension(filePath)
// os.Remove(buildDirectory+"/"+fileName+".html")
f, err := os.OpenFile(buildDirectory+"/"+fileName+".html", os.O_RDWR|os.O_CREATE, 0644)
check(err)
defer f.Close()
// Write to the file
w := bufio.NewWriter(f)
err = tpl.Execute(w,scope)
check(err)
w.Flush()
}
func WatchAceFiles(sourceDirectory,buildDirectory string){
watcher, err := fsnotify.NewWatcher()
check(err)
defer watcher.Close()
done := make(chan bool)
go func(){
for{
select{
case event := <-watcher.Events:
log.Println("Compiling...")
// event.Op => File operation that triggered the event
if event.Op&fsnotify.Write == fsnotify.Write{
log.Println(event.Op)
log.Println(event.Name)
transform(event.Name,buildDirectory)
}
case err := <-watcher.Errors:
check(err)
}
}
}()
check(watcher.Add(sourceDirectory))
<-done // Keeps the function executing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment