arnaucube
arnaucube/konstruiPublic Self-hosted repository
konstrui/fileOperations.go
fileOperations.goRaw
 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"io/ioutil"
 7	"os"
 8	"strings"
 9
10	"github.com/fatih/color"
11)
12
13//dataEntry is the map used to create the array of maps, where the templatejson data is stored
14type dataEntry map[string]string
15
16func copyDirRaw(fromDir string, currentDir string, newDir string) {
17	filesList, _ := ioutil.ReadDir("./" + fromDir + "/" + currentDir)
18	fmt.Println(fromDir + "/" + currentDir)
19	c.Green(newDir + "/" + currentDir)
20	os.MkdirAll(newDir+"/"+currentDir, os.ModePerm)
21	for _, f := range filesList {
22		fileNameSplitted := strings.Split(f.Name(), ".")
23		if len(fileNameSplitted) > 1 {
24			//is a file
25			copyFileRaw(fromDir+"/"+currentDir, f.Name(), newDir+"/"+currentDir)
26		} else {
27			//is a directory
28			copyDirRaw(fromDir+"/"+currentDir, f.Name(), newDir+"/"+currentDir)
29		}
30	}
31}
32
33func copyFileRaw(fromDir string, fName string, newDir string) {
34	c.Yellow("copying raw " + fromDir + "/" + fName)
35	fileContent := readFile(fromDir + "/" + fName)
36	writeFile(newDir+"/"+fName, fileContent)
37}
38
39func readFile(path string) string {
40	dat, err := ioutil.ReadFile(path)
41	check(err)
42	return string(dat)
43}
44
45func getDataFromJson(path string) []dataEntry {
46	var entries []dataEntry
47	file, err := ioutil.ReadFile(path)
48	check(err)
49	content := string(file)
50	var rawEntries []*json.RawMessage
51	json.Unmarshal([]byte(content), &rawEntries)
52	for i := 0; i < len(rawEntries); i++ {
53		rawEntryMarshaled, err := json.Marshal(rawEntries[i])
54		check(err)
55		var newDataEntry map[string]string
56		json.Unmarshal(rawEntryMarshaled, &newDataEntry)
57		entries = append(entries, newDataEntry)
58	}
59
60	return entries
61}
62
63func writeFile(path string, newContent string) {
64	err := ioutil.WriteFile(path, []byte(newContent), 0644)
65	check(err)
66
67	color.Green(path + ":")
68	color.Blue(newContent)
69}
70
71/*func generatePageFromTemplateAndData(templateContent string, entry dataEntry) string {
72	var entryContent string
73	entryContent = templateContent
74	//first, get the map keys
75	var keys []string
76	for key, _ := range entry {
77		keys = append(keys, key)
78	}
79	//now, replace the keys with the values
80	for j := 0; j < len(keys); j++ {
81		entryContent = strings.Replace(entryContent, "{{"+keys[j]+"}}", entry[keys[j]], -1)
82	}
83	return entryContent
84}*/
85func getHtmlAndDataFromRepeatPages(page RepeatPages) (string, []dataEntry) {
86	templateContent := readFile(rawFolderPath + "/" + page.HtmlPage)
87	data := getDataFromJson(rawFolderPath + "/" + page.Data)
88	return templateContent, data
89}