OSDN Git Service

new repo
[bytom/vapor.git] / vendor / golang.org / x / text / internal / testtext / codesize.go
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
5 package testtext
6
7 import (
8         "bytes"
9         "fmt"
10         "io/ioutil"
11         "os"
12         "os/exec"
13         "path/filepath"
14         "runtime"
15 )
16
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:
19 //     package main
20 //     import "golang.org/x/text/somepackage"
21 //     func main() {
22 //         somepackage.Func() // reference Func to cause it to be linked in.
23 //     }
24 // See dict_test.go in the display package for an example.
25 func CodeSize(s string) (int, error) {
26         // Write the file.
27         tmpdir, err := ioutil.TempDir(os.TempDir(), "testtext")
28         if err != nil {
29                 return 0, fmt.Errorf("testtext: failed to create tmpdir: %v", err)
30         }
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)
35         }
36
37         // Build the binary.
38         w := &bytes.Buffer{}
39         cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", "main")
40         cmd.Dir = tmpdir
41         cmd.Stderr = w
42         cmd.Stdout = w
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)
45         }
46
47         // Determine the size.
48         fi, err := os.Stat(filepath.Join(tmpdir, "main"))
49         if err != nil {
50                 return 0, fmt.Errorf("testtext: failed to get file info: %v", err)
51         }
52         return int(fi.Size()), nil
53 }