...
1
2
3
4
5 package testtext
6
7 import (
8 "bytes"
9 "fmt"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "runtime"
14 )
15
16
17
18
19
20
21
22
23
24
25
26 func CodeSize(s string) (int, error) {
27
28 tmpdir, err := os.MkdirTemp(os.TempDir(), "testtext")
29 if err != nil {
30 return 0, fmt.Errorf("testtext: failed to create tmpdir: %v", err)
31 }
32 defer os.RemoveAll(tmpdir)
33 filename := filepath.Join(tmpdir, "main.go")
34 if err := os.WriteFile(filename, []byte(s), 0644); err != nil {
35 return 0, fmt.Errorf("testtext: failed to write main.go: %v", err)
36 }
37
38
39 w := &bytes.Buffer{}
40 cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", "main")
41 cmd.Dir = tmpdir
42 cmd.Stderr = w
43 cmd.Stdout = w
44 if err := cmd.Run(); err != nil {
45 return 0, fmt.Errorf("testtext: failed to execute command: %v\nmain.go:\n%vErrors:%s", err, s, w)
46 }
47
48
49 fi, err := os.Stat(filepath.Join(tmpdir, "main"))
50 if err != nil {
51 return 0, fmt.Errorf("testtext: failed to get file info: %v", err)
52 }
53 return int(fi.Size()), nil
54 }
55
View as plain text