1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
17 // CodeSize builds the given code sample and returns the binary size or en error
18 // if an error occurred. The code sample typically will look like this:
20 // import "golang.org/x/text/somepackage"
22 // somepackage.Func() // reference Func to cause it to be linked in.
24 // See dict_test.go in the display package for an example.
25 func CodeSize(s string) (int, error) {
27 tmpdir, err := ioutil.TempDir(os.TempDir(), "testtext")
29 return 0, fmt.Errorf("testtext: failed to create tmpdir: %v", err)
31 defer os.RemoveAll(tmpdir)
32 filename := filepath.Join(tmpdir, "main.go")
33 if err := ioutil.WriteFile(filename, []byte(s), 0644); err != nil {
34 return 0, fmt.Errorf("testtext: failed to write main.go: %v", err)
39 cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", "main")
43 if err := cmd.Run(); err != nil {
44 return 0, fmt.Errorf("testtext: failed to execute command: %v\nmain.go:\n%vErrors:%s", err, s, w)
47 // Determine the size.
48 fi, err := os.Stat(filepath.Join(tmpdir, "main"))
50 return 0, fmt.Errorf("testtext: failed to get file info: %v", err)
52 return int(fi.Size()), nil