github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmg/SubCommand/goCmd/GoCrossCompile.go (about)

     1  package goCmd
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"path/filepath"
     7  
     8  	"os"
     9  
    10  	"github.com/bronze1man/kmg/kmgCmd"
    11  	"github.com/bronze1man/kmg/kmgConfig"
    12  	"github.com/bronze1man/kmg/kmgConsole"
    13  	"github.com/bronze1man/kmg/kmgFile"
    14  )
    15  
    16  /*
    17  GoCrossComplie [gofile]
    18  the output file will put into $project_root/bin/name_GOOS_GOARCH[.exe]
    19  */
    20  func runGoCrossCompile() {
    21  	command := GoCrossCompile{}
    22  	flag.StringVar(&command.outputPath, "o", "", "output file dir(file name come from source file name),default to $project_root/bin")
    23  	flag.StringVar(&command.version, "v", "", "version string in output file name")
    24  	flag.StringVar(&command.platform, "platform", "", "platform(default use .kmg.yml config)")
    25  	flag.Parse()
    26  
    27  	if len(os.Args) <= 1 {
    28  		kmgConsole.ExitOnErr(fmt.Errorf("need gofile parameter"))
    29  		return
    30  	}
    31  	targetFile := flag.Arg(0)
    32  	kmgc, err := kmgConfig.LoadEnvFromWd()
    33  	kmgConsole.ExitOnErr(err)
    34  	targetName := kmgFile.GetFileBaseWithoutExt(targetFile)
    35  	if command.outputPath == "" {
    36  		command.outputPath = filepath.Join(kmgc.ProjectPath, "bin")
    37  	}
    38  	targetList := []kmgConfig.CompileTarget{}
    39  	if command.platform == "" {
    40  		targetList = kmgc.CrossCompileTarget
    41  	} else {
    42  		targetList = []kmgConfig.CompileTarget{kmgConfig.CompileTarget(command.platform)}
    43  	}
    44  	for _, target := range targetList {
    45  		fileName := ""
    46  		if command.version == "" {
    47  			fileName = targetName + "_" + target.GetGOOS() + "_" + target.GetGOARCH()
    48  		} else {
    49  			fileName = targetName + "_" + command.version + "_" + target.GetGOOS() + "_" + target.GetGOARCH()
    50  		}
    51  
    52  		if target.GetGOOS() == "windows" {
    53  			fileName = fileName + ".exe"
    54  		}
    55  		outputFilePath := filepath.Join(command.outputPath, fileName)
    56  		err := kmgCmd.CmdSlice([]string{"go", "build", "-i", "-o", outputFilePath, targetFile}).
    57  			MustSetEnv("GOOS", target.GetGOOS()).
    58  			MustSetEnv("GOARCH", target.GetGOARCH()).
    59  			MustSetEnv("GOPATH", kmgc.GOPATHToString()).
    60  			Run()
    61  		kmgConsole.ExitOnErr(err)
    62  	}
    63  	return
    64  }
    65  
    66  type GoCrossCompile struct {
    67  	outputPath string
    68  	version    string
    69  	platform   string
    70  }