|
| 1 | +package build |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/Bananenpro/cli" |
| 11 | + cgExec "github.com/code-game-project/codegame-cli/util/exec" |
| 12 | +) |
| 13 | + |
| 14 | +func BuildClient(projectRoot, gameName, output, url string) error { |
| 15 | + out, err := getOutputName(projectRoot, output) |
| 16 | + if err != nil { |
| 17 | + return err |
| 18 | + } |
| 19 | + packageName, err := getPackageName(projectRoot) |
| 20 | + if err != nil { |
| 21 | + return err |
| 22 | + } |
| 23 | + gamePackageName := strings.ReplaceAll(strings.ReplaceAll(gameName, "-", ""), "_", "") |
| 24 | + |
| 25 | + cmdArgs := []string{"build", "-o", out, "-ldflags", fmt.Sprintf("-X %s/%s.URL=%s", packageName, gamePackageName, url), filepath.Join(projectRoot, "main.go")} |
| 26 | + |
| 27 | + _, err = cgExec.Execute(false, "go", cmdArgs...) |
| 28 | + return err |
| 29 | +} |
| 30 | + |
| 31 | +func BuildServer(projectRoot, output string) error { |
| 32 | + out, err := getOutputName(projectRoot, output) |
| 33 | + if err != nil { |
| 34 | + return err |
| 35 | + } |
| 36 | + cmdArgs := []string{"build", "-o", out, filepath.Join(projectRoot, "main.go")} |
| 37 | + _, err = cgExec.Execute(false, "go", cmdArgs...) |
| 38 | + return err |
| 39 | +} |
| 40 | + |
| 41 | +func getOutputName(projectRoot, output string) (string, error) { |
| 42 | + absRoot, err := filepath.Abs(projectRoot) |
| 43 | + if err != nil { |
| 44 | + return "", err |
| 45 | + } |
| 46 | + if output == "" { |
| 47 | + output = filepath.Base(absRoot) |
| 48 | + } |
| 49 | + |
| 50 | + if stat, err := os.Stat(output); err == nil && stat.IsDir() { |
| 51 | + return "", cli.Error("'%s' already exists and is a directory. Specify another output name with '-o <name>'.", output) |
| 52 | + } |
| 53 | + |
| 54 | + return output, nil |
| 55 | +} |
| 56 | + |
| 57 | +func getPackageName(projectRoot string) (string, error) { |
| 58 | + path := filepath.Join(projectRoot, "go.mod") |
| 59 | + file, err := os.Open(path) |
| 60 | + if err != nil { |
| 61 | + return "", cli.Error("Failed to open '%s'", path) |
| 62 | + } |
| 63 | + |
| 64 | + scanner := bufio.NewScanner(file) |
| 65 | + for scanner.Scan() { |
| 66 | + if strings.HasPrefix(scanner.Text(), "module ") { |
| 67 | + return strings.TrimSuffix(strings.TrimPrefix(scanner.Text(), "module "), "/"), nil |
| 68 | + } |
| 69 | + } |
| 70 | + if scanner.Err() != nil { |
| 71 | + cli.Error("Failed to read '%s': %s", path, scanner.Err()) |
| 72 | + } |
| 73 | + return "", cli.Error("Missing 'module' statement in '%s'", path) |
| 74 | +} |
0 commit comments