github.com/go-enjin/golang-org-x-text@v0.12.1-enjin.2/internal/testtext/codesize.go (about)

     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  	"os"
    11  	"os/exec"
    12  	"path/filepath"
    13  	"runtime"
    14  )
    15  
    16  // CodeSize builds the given code sample and returns the binary size or en error
    17  // if an error occurred. The code sample typically will look like this:
    18  //
    19  //	package main
    20  //	import "github.com/go-enjin/golang-org-x-text/somepackage"
    21  //	func main() {
    22  //	    somepackage.Func() // reference Func to cause it to be linked in.
    23  //	}
    24  //
    25  // See dict_test.go in the display package for an example.
    26  func CodeSize(s string) (int, error) {
    27  	// Write the file.
    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  	// Build the binary.
    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  	// Determine the size.
    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  }