go构建项目与打包
package main
import (
"fmt"
"github.com/mattn/go-adb"
"github.com/sirupsen/logrus"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// 定义全局变量
var (
ADBPath string
ADBDevices []*adb.Device
ADBDevice *adb.Device
ADBIP string
ADBPort string
ProjectPath string
BuildCommand = "go build"
)
// 初始化ADB环境
func initADBEnv() {
adb.SetBin("adb") // 设置adb命令的路径
var err error
ADBDevices, err = adb.Devices() // 获取所有连接的设备
if err != nil {
logrus.Fatalf("adb devices failed: %v", err)
}
if len(ADBDevices) == 0 {
logrus.Fatal("no devices connected")
}
ADBDevice = ADBDevices[0] // 默认选择第一个设备
ADBIP = ADBDevice.IP()
ADBPort = ADBDevice.Port()
}
// 构建项目
func buildProject() {
cmd := exec.Command("go", "build") // 构建命令
cmd.Dir = ProjectPath
output, err := cmd.CombinedOutput() // 获取输出和错误信息
if err != nil {
logrus.Fatalf("build failed: %s", output)
}
fmt.Printf("build success: %s\n", output)
}
// 获取项目的绝对路径
func getProjectPath() {
dir, err := filepath.Abs(".") // 获取当前目录的绝对路径
if err != nil {
logrus.Fatalf("get project path failed: %v", err)
}
ProjectPath = dir
}
// 设置GOOS和GOARCH
func setGOOSAndGOARCH(targetOS, targetArch string) {
if targetOS != "" {
os.Setenv("GOOS", targetOS)
}
if targetArch != "" {
os.Setenv("GOARCH", targetArch)
}
}
// 获取目标操作系统和架构
func getTargetOSAndArch(target string) (string, string) {
parts := strings.Split(target, "-")
var targetOS, targetArch string
if len(parts) > 0 {
targetOS = parts[0]
}
if len(parts) > 1 {
targetArch = parts[1]
}
return targetOS, targetArch
}
// 根据目标平台构建项目
func buildForTarget(target string) {
targetOS, targetArch := getTargetOSAndArch(target)
setGOOSAndGOARCH(targetOS, targetArch)
fmt.Printf("building for target: %s\n", target)
buildProject()
}
// 主函数
func main() {
initADBEnv()
getProjectPath()
fmt.Println("Initialization complete.")
fmt.Println("Please enter the target platform for cross-compiling, for example: linux-amd64")
var target string
fmt.Scanln(&target)
buildForTarget(target)
}
这段代码首先导入了必要的Go模块,并定义了全局变量。然后初始化了ADB环境,获取了项目的绝对路径,并提供了构建项目的方法。代码还包含了设置GOOS和GOARCH环境变量的功能,以支持不同操作系统和架构的
评论已关闭