github.com/btcsuite/btcd@v0.24.0/integration/rpctest/btcd.go (about)

     1  // Copyright (c) 2017 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package rpctest
     6  
     7  import (
     8  	"fmt"
     9  	"os/exec"
    10  	"path/filepath"
    11  	"runtime"
    12  	"sync"
    13  )
    14  
    15  var (
    16  	// compileMtx guards access to the executable path so that the project is
    17  	// only compiled once.
    18  	compileMtx sync.Mutex
    19  
    20  	// executablePath is the path to the compiled executable. This is the empty
    21  	// string until btcd is compiled. This should not be accessed directly;
    22  	// instead use the function btcdExecutablePath().
    23  	executablePath string
    24  )
    25  
    26  // btcdExecutablePath returns a path to the btcd executable to be used by
    27  // rpctests. To ensure the code tests against the most up-to-date version of
    28  // btcd, this method compiles btcd the first time it is called. After that, the
    29  // generated binary is used for subsequent test harnesses. The executable file
    30  // is not cleaned up, but since it lives at a static path in a temp directory,
    31  // it is not a big deal.
    32  func btcdExecutablePath() (string, error) {
    33  	compileMtx.Lock()
    34  	defer compileMtx.Unlock()
    35  
    36  	// If btcd has already been compiled, just use that.
    37  	if len(executablePath) != 0 {
    38  		return executablePath, nil
    39  	}
    40  
    41  	testDir, err := baseDir()
    42  	if err != nil {
    43  		return "", err
    44  	}
    45  
    46  	// Build btcd and output an executable in a static temp path.
    47  	outputPath := filepath.Join(testDir, "btcd")
    48  	if runtime.GOOS == "windows" {
    49  		outputPath += ".exe"
    50  	}
    51  	cmd := exec.Command(
    52  		"go", "build", "-o", outputPath, "github.com/btcsuite/btcd",
    53  	)
    54  	err = cmd.Run()
    55  	if err != nil {
    56  		return "", fmt.Errorf("Failed to build btcd: %v", err)
    57  	}
    58  
    59  	// Save executable path so future calls do not recompile.
    60  	executablePath = outputPath
    61  	return executablePath, nil
    62  }