-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
178 lines (150 loc) · 4.1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"github.com/snabb/sitemap"
"github.com/spf13/viper"
)
var maxPerSitemap = 49999
var arguments = os.Args
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func dirExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
func main() {
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.SetConfigName("config")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
log.Fatalf("config.yaml not found")
} else {
// Config file was found but another error was produced
log.Fatalf("There is an issue with your config.yaml file")
}
}
baseURL := viper.Get("baseURL")
sitemapPrefix := viper.Get("sitemapPrefix")
sitemapSuffix := viper.Get("sitemapSuffix")
sitemapDir := viper.Get("sitemapDir")
// delete sitemaps dir if it already exists
directoryExists, err := dirExists("sitemaps")
if err != nil {
log.Println(err)
}
if directoryExists {
os.RemoveAll("sitemaps")
}
// retrieve file name from Args
// and handle error if user fails pass an arg or passes too many
var csvFile string
if len(arguments) == 2 {
csvFile = arguments[1]
} else if len(arguments) < 2 {
log.Fatalf("Please include a file name as an argument")
} else {
log.Fatalf("Too many arguments!")
}
// read CSV file
sliceOfCSVLines, err := readLines(csvFile)
if err != nil {
log.Fatalf("readLines: %s", err)
}
// create map of slices corresponding to each sitemap's content
mapOfSitemapContents := make(map[int][]string)
mapIndex := 0
for ind, el := range sliceOfCSVLines {
// formatting
sliceOfStrings := strings.Split(el, ",")
sliceNames := sliceOfStrings[:len(sliceOfStrings)-1]
url := fmt.Sprintf("%v/%v-%v/", baseURL, strings.ToLower(sliceNames[1]), strings.ToLower(sliceNames[0]))
// limit # of records (blocks of 49,999)
if ind < (maxPerSitemap*mapIndex + maxPerSitemap) {
mapOfSitemapContents[mapIndex] = append(mapOfSitemapContents[mapIndex], url)
} else {
mapIndex++
}
}
// create sitemap index
sitemapIndex := sitemap.NewSitemapIndex()
// create sitemap dir
err = os.Mkdir("sitemaps", 0755)
if err != nil {
fmt.Println(err)
}
// create sitemap index file
f, err := os.Create(fmt.Sprintf("%v/sitemap.xml", sitemapDir))
if err != nil {
fmt.Println(err)
return
}
for key, el := range mapOfSitemapContents {
// add entries to sitemap index
sitemapIndex.Add(&sitemap.URL{
Loc: fmt.Sprintf("%v%v%v.gz", sitemapPrefix, key, sitemapSuffix),
})
// create a sitemap for every index of the map
sm := sitemap.New()
for _, innerEl := range el {
sm.Add(&sitemap.URL{
Loc: innerEl,
})
}
// create individual sitemap files in appropriate dir (ensure that this matches name of files created above)
f, err := os.Create(fmt.Sprintf("%v/%v%v%v", sitemapDir, sitemapPrefix, key, sitemapSuffix))
if err != nil {
fmt.Println(err)
return
}
// write to individual sitemap files after populating them
sm.WriteTo(f)
}
// write to sitemap index after it's been populated with entries
sitemapIndex.WriteTo(f)
fmt.Println("Sitemaps created")
// gzip individual sitemaps
files, err := ioutil.ReadDir(fmt.Sprintf("./%v", sitemapDir))
if err != nil {
log.Fatal(err)
}
for _, file := range files {
// exclude sitemap index from being gzipped (only perform if file contains specified prefix)
if strings.HasPrefix(file.Name(), sitemapPrefix.(string)) {
cmd := exec.Command("gzip", fmt.Sprintf("%v/%v", sitemapDir, file.Name()))
var stderr bytes.Buffer
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
return
}
}
}
fmt.Println("Sitemaps gzipped")
}