goStringsReplacer/main.go
main.goRaw
1package main
2
3import (
4 "bufio"
5 "fmt"
6 "io/ioutil"
7 "os"
8 "strings"
9)
10
11const rawFolderPath = "./originalFiles"
12const newFolderPath = "./newFiles"
13
14func check(err error) {
15 if err != nil {
16 fmt.Println(err)
17 }
18}
19
20func replaceFromTable(table map[string]string, originalContent string) string {
21 var newContent string
22 newContent = originalContent
23 for i := 0; i < len(table); i++ {
24 //first, get the map keys
25 var keys []string
26 for key, _ := range table {
27 keys = append(keys, key)
28 }
29 //now, replace the keys with the values
30 for i := 0; i < len(keys); i++ {
31 newContent = strings.Replace(newContent, keys[i], table[keys[i]], -1)
32 }
33 }
34 return newContent
35
36}
37func readConfigTable(path string) map[string]string {
38 table := make(map[string]string)
39 f, err := os.Open(path)
40 check(err)
41 scanner := bufio.NewScanner(f)
42 for scanner.Scan() {
43 currentLine := scanner.Text()
44 if currentLine != "" {
45 val1 := strings.Split(currentLine, " ")[0]
46 val2 := strings.Split(currentLine, " ")[1]
47 table[val1] = val2
48 }
49 }
50 return table
51}
52
53func readFile(folderPath string, filename string) string {
54 dat, err := ioutil.ReadFile(folderPath + "/" + filename)
55 check(err)
56 return string(dat)
57}
58
59func writeFile(path string, newContent string) {
60 err := ioutil.WriteFile(path, []byte(newContent), 0644)
61 check(err)
62}
63
64func parseDir(folderPath string, newDir string, table map[string]string) {
65 files, _ := ioutil.ReadDir(folderPath)
66 for _, f := range files {
67 fileNameSplitted := strings.Split(f.Name(), ".")
68 if len(fileNameSplitted) == 1 {
69 newDir := newDir + "/" + f.Name()
70 oldDir := rawFolderPath + "/" + f.Name()
71 if _, err := os.Stat(newDir); os.IsNotExist(err) {
72 _ = os.Mkdir(newDir, 0700)
73 }
74 parseDir(oldDir, newDir, table)
75 } else {
76 fileContent := readFile(folderPath, f.Name())
77 newContent := replaceFromTable(table, fileContent)
78 writeFile(newDir+"/"+f.Name(), newContent)
79 fmt.Println(newDir + "/" + f.Name())
80 }
81 }
82}
83
84func main() {
85 table := readConfigTable("replacerConfig.txt")
86 fmt.Println(table)
87 parseDir(rawFolderPath, newFolderPath, table)
88}