|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "net/http" |
| 6 | + "os" |
| 7 | + "os/exec" |
| 8 | + "path/filepath" |
| 9 | + "runtime" |
| 10 | + "testing" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + // renovate: datasource=github-releases depName=ocm packageName=open-component-model/ocm |
| 15 | + OCM_VERSION = "0.27.0" |
| 16 | +) |
| 17 | + |
| 18 | +// DownloadOCMAndAddToPath downloads the OCM cli for the current platform and puts it to the PATH of the test |
| 19 | +func DownloadOCMAndAddToPath(t *testing.T) { |
| 20 | + t.Helper() |
| 21 | + |
| 22 | + downloadURL := "https://github.com/open-component-model/ocm/releases/download/v" + |
| 23 | + OCM_VERSION + "/ocm-" + OCM_VERSION + "-" + runtime.GOOS + "-" + runtime.GOARCH + ".tar.gz" |
| 24 | + |
| 25 | + tempDir := t.TempDir() |
| 26 | + archivePath := filepath.Join(tempDir, "ocm.tar.gz") |
| 27 | + out, err := os.Create(archivePath) |
| 28 | + if err != nil { |
| 29 | + t.Fatalf("failed to create file: %v", err) |
| 30 | + } |
| 31 | + defer out.Close() |
| 32 | + |
| 33 | + resp, err := http.Get(downloadURL) |
| 34 | + if err != nil { |
| 35 | + t.Fatalf("failed to download ocm: %v", err) |
| 36 | + } |
| 37 | + defer resp.Body.Close() |
| 38 | + |
| 39 | + _, err = io.Copy(out, resp.Body) |
| 40 | + if err != nil { |
| 41 | + t.Fatalf("failed to save ocm: %v", err) |
| 42 | + } |
| 43 | + |
| 44 | + // Extract the tar.gz |
| 45 | + cmd := exec.Command("tar", "-xzf", archivePath, "-C", tempDir) |
| 46 | + if err := cmd.Run(); err != nil { |
| 47 | + t.Fatalf("failed to extract ocm: %v", err) |
| 48 | + } |
| 49 | + |
| 50 | + // Find the ocm binary |
| 51 | + ocmPath := filepath.Join(tempDir, "ocm") |
| 52 | + if _, err := os.Stat(ocmPath); err != nil { |
| 53 | + t.Fatalf("ocm binary not found after extraction: %v", err) |
| 54 | + } |
| 55 | + |
| 56 | + t.Setenv("PATH", tempDir+":"+os.Getenv("PATH")) |
| 57 | +} |
| 58 | + |
| 59 | +// BuildComponent builds the component for the specified componentConstructorLocation and returns the ctf out directory. |
| 60 | +func BuildComponent(componentConstructorLocation string, t *testing.T) string { |
| 61 | + tempDir := t.TempDir() |
| 62 | + ctfDir := filepath.Join(tempDir, "ctf") |
| 63 | + |
| 64 | + cmd := exec.Command("ocm", []string{ |
| 65 | + "add", |
| 66 | + "componentversions", |
| 67 | + "--create", |
| 68 | + "--file", |
| 69 | + ctfDir, |
| 70 | + componentConstructorLocation}...) |
| 71 | + |
| 72 | + out, err := cmd.CombinedOutput() |
| 73 | + t.Log("OCM Output:", string(out)) |
| 74 | + if err != nil { |
| 75 | + t.Fatalf("failed to build component: %v", err) |
| 76 | + } |
| 77 | + |
| 78 | + return ctfDir |
| 79 | +} |
0 commit comments