summaryrefslogtreecommitdiff
path: root/cmd/generate/main.go
blob: 67e745cfdee8a884f6b3696da4d1570374c085b7 (plain) (blame)
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package main

import (
	"bytes"
	"errors"
	"fmt"
	"go/ast"
	"go/parser"
	"go/scanner"
	"go/token"
	"io"
	"net/http"
	"os"
	"reflect"
	"slices"
	"strconv"
	"strings"
)

func main() {
	if err := run(); err != nil {
		panic(err)
	}
}

func slice(fileContents string, filePosInfo *token.File, start token.Pos, end token.Pos) string {
	return fileContents[filePosInfo.Position(start).Offset:filePosInfo.Position(end).Offset]
}

func run() error {
	filename := "examples/basic.go"
	fileBytes, err := os.ReadFile(filename)
	if err != nil {
		return err
	}
	// fileContents := string(fileBytes)
	var fset token.FileSet
	fp := fset.AddFile(filename, -1, len(fileBytes))
	_ = fp
	f, err := parser.ParseFile(&fset, "examples/basic.go", fileBytes, parser.ParseComments|parser.SkipObjectResolution)
	if err != nil {
		return err
	}
	var output bytes.Buffer
	output.WriteString("package ")
	output.WriteString(f.Name.Name)
	output.WriteByte('\n')
	for _, decl := range f.Decls {
		f, ok := decl.(*ast.FuncDecl)
		if !ok {
			continue
		}
		if f.Doc == nil {
			continue
		}
		hhRoute := f.Doc.List[len(f.Doc.List)-1].Text
		var routeSpec string
		if routeSpec, ok = strings.CutPrefix(hhRoute, "//hh:route "); !ok {
			continue
		}
		split := strings.Split(routeSpec, " ")
		var method, path string
		if len(split) == 1 {
			path = split[0]
		} else if len(split) == 2 {
			method = split[0]
			path = split[1]
		} else {
			return errors.New("Invalid route spec. Expected `//hh:route [method] [path]` or `//hh:route [path]`")
		}
		if !slices.ContainsFunc([]string{
			"",
			http.MethodGet,
			http.MethodHead,
			http.MethodPost,
			http.MethodPut,
			http.MethodPatch,
			http.MethodDelete,
			http.MethodConnect,
			http.MethodOptions,
			http.MethodTrace,
		}, func(m string) bool { return m == method }) {
			return errors.New("Invalid http method " + method)
		}
		output.WriteString("\nfunc hh_")
		output.WriteString(f.Name.String())
		output.WriteString("[S any](s S, w http.ResponseWriter, r *http.Request) {")
		parsedRequestType, ok := f.Type.Params.List[1].Type.(*ast.StructType)
		if !ok {
			return errors.New("Parsed request type must be a struct")
		}
		for _, field := range parsedRequestType.Fields.List {
			for _, nameIdent := range field.Names {
				typ := field.Type
				name := nameIdent.Name
				var tag string
				if field.Tag != nil {
					tag = reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get("hh")
				}
				fmt.Println(typ, name, tag)
				tags := strings.Split(tag, ",")
				// TODO: handle raw request. Or maybe that should be a separate parameter
				if len(tags) == 0 {
					return errors.New("Don't know what to do with '" + name + "'. You must add a tag to specify")
				}
				switch tags[0] {
				case "form":
					output.WriteString("\n\t")
					output.WriteString(name)
					output.WriteString(" := r.FormValue(\"")
					output.WriteString(name)
					output.WriteString("\")")
				case "cookie":
					// panic("todo")
				}
			}
		}
		i := 0
		output.WriteString("\n\t")
		output.WriteString(f.Name.Name)
		output.WriteString("(w, ")
		i = 0
		for _, field := range parsedRequestType.Fields.List {
			for _, nameIdent := range field.Names {
				typ := field.Type
				name := nameIdent.Name
				if i > 0 {
					output.WriteString(", ")
				}
				output.WriteString("var")
				output.WriteString(strconv.Itoa(i))
				i++
			}
		}
		output.WriteString(")\n")
		output.WriteString("}\n")

		fmt.Printf("`%v`\n`%v`\n", path, f.Name.Name)
	}
	io.Copy(os.Stdout, &output)
	return nil
}

type routeSpec struct {
	method     string
	path       string
	parameters []routeSpecParam
}

type routeSpecParam struct {
	name      string
	extractor string
}

func parseRouteSpec(s string) (routeSpec, error) {
	s = strings.TrimRight(s, " \n")
	var rs routeSpec
	for _, method := range []string{
		http.MethodGet,
		http.MethodHead,
		http.MethodPost,
		http.MethodPut,
		http.MethodPatch,
		http.MethodDelete,
		http.MethodConnect,
		http.MethodOptions,
		http.MethodTrace,
	} {
		if rest, ok := strings.CutPrefix(s, method+" "); ok {
			s = rest
			rs.method = method
			break
		}
	}

	for {
		if commaPos := strings.IndexByte(s, ','); commaPos != -1 {
			rs.path = s[:commaPos]
			s = s[commaPos+1:]
		} else {
			rs.path = s
			return rs, nil
		}

		s = strings.TrimLeft(s, " ")
		if s == "" {
			break
		}

		end := -1
		for i := 0; i < len(s); i++ {
			if 'a' <= s[i] && s[i] <= 'z' ||
				'A' <= s[i] && s[i] <= 'Z' ||
				s[i] == '_' {
				continue
			}
			if s[i] == ':' {
				end = i
				break
			}
			return rs, errors.New("Expected ':' to mark end of parameter name, got " + s[i:i+1])
		}
		if end == -1 {
			return rs, errors.New("Expected ':' to mark end of parameter name, got end of line")
		}
		var p routeSpecParam
		p.name = s[:end]
		s = s[end+1:]

		s = strings.TrimLeft(s, " ")

		expr, err := parser.ParseExpr(s)
		if el, ok := err.(scanner.ErrorList); err == nil || ok && el[0].Msg == "expected 'EOF', found ','" {
			switch expr := expr.(type) {
			case *ast.Ident:
				switch expr.Name {
				case "query":
					p.extractor = ":" + expr.Name
				default:
					return rs, errors.New("Unexpected extractor " + expr.Name)
				}
			case *ast.CallExpr:
				p.extractor = s[expr.Pos()-1 : expr.End()-1]
			default:
				return rs, errors.New("Unexpected extractor" + s[expr.Pos()-1:expr.End()-1])
			}
		} else {
			return rs, err
		}
		s = s[expr.End()-1:]

		rs.parameters = append(rs.parameters, p)
	}

	return rs, nil
}