forked from EngineerBetter/hugo-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (85 loc) · 2.32 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
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
shutil "github.com/termie/go-shutil"
yaml "gopkg.in/yaml.v2"
)
type Mapping struct {
Name string
Exercises []string
}
type Structure struct {
Mappings []Mapping
}
func check(e error) {
if e != nil {
panic(e)
}
}
func cleanDirectory(dir string) {
files, _ := filepath.Glob(dir + "/*")
for _, file := range files {
os.RemoveAll(file)
}
}
func exists(path string) bool {
_, err := os.Stat(path)
if err != nil && os.IsNotExist(err) {
return false
}
return true
}
func main() {
if len(os.Args) != 4 {
log.Fatalln("Usage: hugo-parser path/to/structure.yml path/to/source/dir path/to/target/dir ")
}
filename := os.Args[1]
sourceDir := os.Args[2]
targetDir := os.Args[3]
mappingContents, err := ioutil.ReadFile(filename)
check(err)
fmt.Print(string(mappingContents))
structure := Structure{}
err = yaml.Unmarshal(mappingContents, &structure)
if err != nil {
log.Fatal("Unable to unmarshal " + filename)
}
learningPath := fmt.Sprintf("%s/learning-path", sourceDir)
exercisePath := fmt.Sprintf("%s/exercises", sourceDir)
cleanDirectory(targetDir)
fileInfo, err := os.Lstat(sourceDir)
mode := fileInfo.Mode()
if !exists(targetDir) {
os.MkdirAll(targetDir, mode)
}
for i, mapping := range structure.Mappings {
index := fmt.Sprintf("%02d", i+1)
fullSrc := learningPath + "/" + mapping.Name + "/index.md"
fullTgtDir := targetDir + "/" + index + "-" + mapping.Name
fullTgt := fullTgtDir + "/_index.md"
if !exists(fullTgtDir) {
os.MkdirAll(fullTgtDir, mode)
}
fmt.Println(fullSrc + " to " + fullTgt)
err = shutil.CopyFile(fullSrc, fullTgt, false)
check(err)
for j, exercise := range mapping.Exercises {
subIndex := fmt.Sprintf("%02d", j+1)
fullSrc := exercisePath + "/" + exercise + "/README.md"
fullTgt := targetDir + "/" + index + "-" + mapping.Name + "/" + subIndex + "-" + exercise + ".md"
fmt.Println(fullSrc + " to " + fullTgt)
err = shutil.CopyFile(fullSrc, fullTgt, false)
check(err)
fullSrcImages := exercisePath + "/" + exercise + "/images"
if _, err := os.Stat(fullSrcImages); err == nil {
fullTgtImages := targetDir + "/" + index + "-" + mapping.Name + "/" + subIndex + "-" + exercise + "/images"
err = shutil.CopyTree(fullSrcImages, fullTgtImages, nil)
check(err)
}
}
}
}