-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathmain.go
More file actions
64 lines (56 loc) · 1.7 KB
/
main.go
File metadata and controls
64 lines (56 loc) · 1.7 KB
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
package main
import (
"fmt"
"go/format"
"log"
"os"
"strings"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
// This code fixes the generated mock service server code to properly embed
// the necessary unimplemented struct and add the interface assertion
if len(os.Args) != 3 {
return fmt.Errorf("must provide service name and code filename as arguments")
}
// Read file
b, err := os.ReadFile(os.Args[2])
if err != nil {
return fmt.Errorf("unable to read file: %w", err)
}
source := string(b)
serviceName := os.Args[1]
// Find the first "Server struct {" location
toFind := fmt.Sprintf("Mock%vServer struct {\n", serviceName)
structIndex := strings.Index(source, toFind)
if structIndex < 0 || strings.LastIndex(source, toFind) != structIndex {
return fmt.Errorf("expected single server struct in file")
}
structIndex += len(toFind)
// At the first newline we need to embed the unimplemented server
source = source[:structIndex] +
fmt.Sprintf("\t%v.Unimplemented%vServer\n", strings.ToLower(serviceName), serviceName) +
source[structIndex:]
// After the closing brace, we need to add the type assertion to ensure
// interface conformance
endBrace := structIndex + strings.Index(source[structIndex:], "\n}\n") + 3
source = source[:endBrace] +
fmt.Sprintf(
"\nvar _ %v.%vServer = (*Mock%vServer)(nil)\n\n",
strings.ToLower(serviceName),
serviceName,
serviceName,
) +
source[endBrace:]
// Format and write
if b, err := format.Source([]byte(source)); err != nil {
return fmt.Errorf("failed formatting: %w", err)
} else if err := os.WriteFile(os.Args[2], b, 0644); err != nil {
return fmt.Errorf("failed writing: %w", err)
}
return nil
}