You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.0 KiB

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