-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen.go
112 lines (88 loc) · 2.61 KB
/
gen.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
// The following directive is necessary to make the package coherent:
// +build ignore
// This program generates contributors.go. It can be invoked by running
// go generate
package main
import (
"bufio"
"encoding/json"
"io/ioutil"
"log"
"os"
"strings"
)
type GenRoute struct {
Method string `json:"method"`
Route string `json:"route"`
Middleware string `json:"middleware"`
Function string
}
func main() {
d, _ := os.Getwd()
path := d + "/controllers"
files, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
os.Remove(d + "/routes/web.go")
createPath := d + "/routes/web.go"
routeFile, _ := os.Create(createPath)
defer routeFile.Close()
w := bufio.NewWriter(routeFile)
defer w.Flush()
var middlewareString string
finalStringToWrite := "package routes\n\nimport (\n\tflameroutes \"github.com/mitchdennett/flameframework/routes\"\n\t\"github.com/mitchdennett/flameproject/controllers\"\n" + middlewareString + ")\n\nvar Routes = []flameroutes.Route{\n "
//Some great spaghetti code. This really needs to be refactored.
for _, f := range files {
if !f.IsDir() {
f, _ := os.Open(path + "/" + f.Name())
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "//") {
slice := strings.Split(line, "routemeta:")
if len(slice) > 1 {
var route GenRoute
if err := json.Unmarshal([]byte(strings.Trim(slice[1], " ")), &route); err != nil {
panic(err)
} else {
scanner.Scan()
nextLine := scanner.Text()
if strings.HasPrefix(nextLine, "func") {
nextLine = strings.TrimPrefix(nextLine, "func ")
splitArr := strings.Split(nextLine, "(")
if len(splitArr) > 1 {
nextLine = splitArr[0]
route.Function = nextLine
// Need to implement middleware
// if route.Middleware != "" {
// middlewareString = "\t\"github.com/mitchdennett/flameproject/middleware\"\n"
// }
stringToWrite := generateRoute(route)
//w.WriteString(stringToWrite)
finalStringToWrite += stringToWrite
}
}
}
}
}
}
f.Close()
}
}
w.WriteString(finalStringToWrite + "}")
}
func generateRoute(route GenRoute) string {
var routeString string
switch os := strings.ToUpper(route.Method); os {
case "GET":
routeString = "\tflameroutes.Get()"
case "POST":
routeString = "\tflameroutes.Post()"
default:
routeString = "\tflameroutes.Get()"
}
routeString += `.Define("` + route.Route + `", controllers.` + route.Function + `),` + "\n"
return routeString
}