arnaucube
arnaucube/blogoPublic Self-hosted repository
blogo/files.go
files.goRaw
  1package main
  2
  3import (
  4	"fmt"
  5	"io/ioutil"
  6	"log"
  7	"os"
  8	"os/exec"
  9	"path/filepath"
 10	"strings"
 11
 12	"github.com/fatih/color"
 13	"github.com/fsnotify/fsnotify"
 14)
 15
 16func readFile(path string) string {
 17	dat, err := ioutil.ReadFile(path)
 18	if err != nil {
 19		color.Red(path)
 20	}
 21	check(err)
 22	return string(dat)
 23}
 24
 25func writeFile(path string, newContent string) {
 26	err := ioutil.WriteFile(path, []byte(newContent), 0644)
 27	check(err)
 28
 29	color.Green(path)
 30	//color.Blue(newContent)
 31}
 32
 33func getLines(text string) []string {
 34	lines := strings.Split(text, "\n")
 35	return lines
 36}
 37
 38func concatStringsWithJumps(lines []string) string {
 39	var r string
 40	for _, l := range lines {
 41		r = r + l + "\n"
 42	}
 43	return r
 44}
 45
 46func copyRaw(original string, destination string) {
 47	color.Green(original + " --> to --> " + destination)
 48	_, err := exec.Command("cp", "-rf", original, destination).Output()
 49	check(err)
 50}
 51
 52var watcherInputFiles, watcherPublic *fsnotify.Watcher
 53
 54func watch(dir string) {
 55	var err error
 56	var watcher *fsnotify.Watcher
 57	if dir == "./blogo-input" {
 58		watcherInputFiles, err = fsnotify.NewWatcher()
 59		if err != nil {
 60			log.Fatal(err)
 61		}
 62		watcher = watcherInputFiles
 63	} else {
 64		watcherPublic, err = fsnotify.NewWatcher()
 65		if err != nil {
 66			log.Fatal(err)
 67		}
 68		watcher = watcherPublic
 69	}
 70
 71	defer watcher.Close()
 72
 73	if dir == "./blogo-input" {
 74		if err := filepath.Walk(dir, watchInputFilesDir); err != nil {
 75			log.Fatal(err)
 76		}
 77	} else {
 78		if err := filepath.Walk(dir, watchPublicDir); err != nil {
 79			log.Fatal(err)
 80		}
 81	}
 82
 83	for {
 84		select {
 85		case event := <-watcher.Events:
 86			fmt.Printf("file system event: %#v\n", event)
 87			if dir == "./blogo-input" {
 88				generateHTML()
 89			}
 90		case err := <-watcher.Errors:
 91			log.Fatal("file system watcher error:", err)
 92		}
 93	}
 94}
 95
 96// watchInputFilesDir gets run as a walk func, searching for directories to add watchers to
 97func watchInputFilesDir(path string, fi os.FileInfo, err error) error {
 98	if fi.Mode().IsDir() {
 99		return watcherInputFiles.Add(path)
100	}
101
102	return nil
103}
104
105// watchPublicDir gets run as a walk func, searching for directories to add watchers to
106func watchPublicDir(path string, fi os.FileInfo, err error) error {
107	if fi.Mode().IsDir() {
108		return watcherPublic.Add(path)
109	}
110
111	return nil
112}