You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

54 lines
1.5 KiB

  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.
  4. package testtext
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "runtime"
  13. )
  14. // CodeSize builds the given code sample and returns the binary size or en error
  15. // if an error occurred. The code sample typically will look like this:
  16. // package main
  17. // import "golang.org/x/text/somepackage"
  18. // func main() {
  19. // somepackage.Func() // reference Func to cause it to be linked in.
  20. // }
  21. // See dict_test.go in the display package for an example.
  22. func CodeSize(s string) (int, error) {
  23. // Write the file.
  24. tmpdir, err := ioutil.TempDir(os.TempDir(), "testtext")
  25. if err != nil {
  26. return 0, fmt.Errorf("testtext: failed to create tmpdir: %v", err)
  27. }
  28. defer os.RemoveAll(tmpdir)
  29. filename := filepath.Join(tmpdir, "main.go")
  30. if err := ioutil.WriteFile(filename, []byte(s), 0644); err != nil {
  31. return 0, fmt.Errorf("testtext: failed to write main.go: %v", err)
  32. }
  33. // Build the binary.
  34. w := &bytes.Buffer{}
  35. cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", "main")
  36. cmd.Dir = tmpdir
  37. cmd.Stderr = w
  38. cmd.Stdout = w
  39. if err := cmd.Run(); err != nil {
  40. return 0, fmt.Errorf("testtext: failed to execute command: %v\nmain.go:\n%vErrors:%s", err, s, w)
  41. }
  42. // Determine the size.
  43. fi, err := os.Stat(filepath.Join(tmpdir, "main"))
  44. if err != nil {
  45. return 0, fmt.Errorf("testtext: failed to get file info: %v", err)
  46. }
  47. return int(fi.Size()), nil
  48. }