1package cli
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "os/exec"
8 "regexp"
9 "strings"
10
11 "github.com/spf13/cobra"
12
13 "github.com/bnema/gordon/internal/adapters/in/cli/remote"
14 "github.com/bnema/gordon/internal/adapters/in/cli/ui/components"
15 "github.com/bnema/gordon/internal/adapters/in/cli/ui/styles"
16 "github.com/bnema/gordon/pkg/validation"
17)
18
19func newPushCmd() *cobra.Command {
20 var (
21 noDeploy bool
22 noConfirm bool
23 build bool
24 platform string
25 tag string
26 buildArgs []string
27 )
28
29 cmd := &cobra.Command{
30 Use: "push <domain>",
31 Short: "Tag, push, and optionally deploy an image",
32 Long: `Tags a local image for the Gordon registry and pushes it.
33Uses git tags for versioning. Optionally triggers deployment after push.
34
35With --build, builds the image first using docker buildx.
36
37Examples:
38 gordon push myapp.example.com --remote ...
39 gordon push myapp.example.com --build --remote ...
40 gordon push myapp.example.com --tag v1.2.0 --no-deploy --remote ...
41 gordon push myapp.example.com --build --build-arg CGO_ENABLED=0 --remote ...`,
42 Args: cobra.ExactArgs(1),
43 RunE: func(cmd *cobra.Command, args []string) error {
44 return runPush(cmd.Context(), args[0], tag, build, platform, buildArgs, noDeploy, noConfirm)
45 },
46 }
47
48 cmd.Flags().BoolVar(&noDeploy, "no-deploy", false, "Push only, don't trigger deploy")
49 cmd.Flags().BoolVar(&noConfirm, "no-confirm", false, "Skip deploy confirmation prompt")
50 cmd.Flags().BoolVar(&build, "build", false, "Build the image first using docker buildx")
51 cmd.Flags().StringVar(&platform, "platform", "linux/amd64", "Target platform (used with --build)")
52 cmd.Flags().StringVar(&tag, "tag", "", "Override version tag (default: git describe)")
53 cmd.Flags().StringArrayVar(&buildArgs, "build-arg", nil, "Additional build args (used with --build)")
54
55 return cmd
56}
57
58func runPush(ctx context.Context, pushDomain, tag string, build bool, platform string, buildArgs []string, noDeploy bool, noConfirm bool) error {
59 client, isRemote := GetRemoteClient()
60 if !isRemote {
61 return fmt.Errorf("push requires remote mode")
62 }
63
64 route, err := client.GetRoute(ctx, pushDomain)
65 if err != nil {
66 return fmt.Errorf("failed to get route: %w", err)
67 }
68
69 registry, imageName, _ := parseImageRef(route.Image)
70 if registry == "" || imageName == "" {
71 return fmt.Errorf("cannot parse registry/image from route image: %s", route.Image)
72 }
73
74 version := determineVersion(ctx, tag)
75 if version != "latest" {
76 if err := validation.ValidateReference(version); err != nil {
77 return fmt.Errorf("invalid version tag %q: %w", version, err)
78 }
79 }
80
81 for _, ba := range buildArgs {
82 if err := validateBuildArg(ba); err != nil {
83 return err
84 }
85 }
86
87 versionRef := fmt.Sprintf("%s/%s:%s", registry, imageName, version)
88 latestRef := fmt.Sprintf("%s/%s:latest", registry, imageName)
89
90 fmt.Printf("Image: %s\n", styles.Theme.Bold.Render(versionRef))
91 if version != "latest" {
92 fmt.Printf("Also: %s\n", styles.Theme.Bold.Render(latestRef))
93 }
94
95 if build {
96 if err := buildAndPush(ctx, version, platform, buildArgs, versionRef, latestRef); err != nil {
97 return err
98 }
99 } else {
100 if err := tagAndPush(ctx, registry, imageName, version, versionRef, latestRef); err != nil {
101 return err
102 }
103 }
104
105 fmt.Println(styles.RenderSuccess("Push complete"))
106
107 if !noDeploy {
108 return deployAfterPush(ctx, client, pushDomain, noConfirm)
109 }
110
111 return nil
112}
113
114func determineVersion(ctx context.Context, tag string) string {
115 version := tag
116 if version == "" {
117 version = getGitVersion(ctx)
118 }
119 if version == "" {
120 version = "latest"
121 }
122 return version
123}
124
125func buildAndPush(ctx context.Context, version, platform string, buildArgs []string, versionRef, latestRef string) error {
126 if _, err := os.Stat("Dockerfile"); os.IsNotExist(err) {
127 return fmt.Errorf("no Dockerfile found in current directory")
128 }
129
130 fmt.Println("\nBuilding and pushing...")
131 args := []string{
132 "buildx", "build",
133 "--platform", platform,
134 "-t", latestRef,
135 "--build-arg", "VERSION=" + version,
136 }
137 if version != "latest" {
138 args = append(args, "-t", versionRef)
139 }
140 for _, ba := range buildArgs {
141 args = append(args, "--build-arg", ba)
142 }
143 args = append(args, "--push", ".")
144
145 dockerCmd := exec.CommandContext(ctx, "docker", args...) // #nosec G204
146 dockerCmd.Stdout = os.Stdout
147 dockerCmd.Stderr = os.Stderr
148 if err := dockerCmd.Run(); err != nil {
149 return fmt.Errorf("docker buildx failed: %w", err)
150 }
151 return nil
152}
153
154func tagAndPush(ctx context.Context, registry, imageName, version, versionRef, latestRef string) error {
155 localImage := fmt.Sprintf("%s/%s", registry, imageName)
156
157 fmt.Println("\nChecking local image...")
158 if !dockerImageExists(ctx, localImage) {
159 return fmt.Errorf("local image %s not found; build and tag it before pushing", localImage)
160 }
161
162 fmt.Println("Tagging...")
163 if err := dockerTag(ctx, localImage, versionRef); err != nil {
164 return fmt.Errorf("failed to tag %s: %w", versionRef, err)
165 }
166 if version != "latest" {
167 if err := dockerTag(ctx, localImage, latestRef); err != nil {
168 return fmt.Errorf("failed to tag %s: %w", latestRef, err)
169 }
170 }
171
172 fmt.Println("Pushing...")
173 if err := dockerPush(ctx, versionRef); err != nil {
174 return fmt.Errorf("failed to push %s: %w", versionRef, err)
175 }
176 if version != "latest" {
177 if err := dockerPush(ctx, latestRef); err != nil {
178 return fmt.Errorf("failed to push %s: %w", latestRef, err)
179 }
180 }
181 return nil
182}
183
184func deployAfterPush(ctx context.Context, client *remote.Client, pushDomain string, noConfirm bool) error {
185 if !noConfirm {
186 confirmed, err := components.RunConfirm("Deploy now?", components.WithDefaultYes())
187 if err != nil {
188 return err
189 }
190 if !confirmed {
191 return nil
192 }
193 }
194
195 result, err := client.Deploy(ctx, pushDomain)
196 if err != nil {
197 return fmt.Errorf("failed to deploy: %w", err)
198 }
199 containerID := result.ContainerID
200 if len(containerID) > 12 {
201 containerID = containerID[:12]
202 }
203 fmt.Println(styles.RenderSuccess(fmt.Sprintf("Deployed %s (container: %s)", pushDomain, containerID)))
204 return nil
205}
206
207// parseImageRef splits "registry/name:tag" into components.
208func parseImageRef(image string) (registry, name, tag string) {
209 // Handle "reg.bnema.dev/jp-bot:latest" or "reg.bnema.dev/jp-bot"
210 parts := strings.SplitN(image, "/", 2)
211 if len(parts) != 2 {
212 return "", "", ""
213 }
214 registry = parts[0]
215 nameTag := parts[1]
216 if idx := strings.LastIndex(nameTag, ":"); idx != -1 {
217 name = nameTag[:idx]
218 tag = nameTag[idx+1:]
219 } else {
220 name = nameTag
221 tag = "latest"
222 }
223 return
224}
225
226// getGitVersion returns the latest git tag, or empty string if unavailable.
227func getGitVersion(ctx context.Context) string {
228 out, err := exec.CommandContext(ctx, "git", "describe", "--tags", "--abbrev=0").Output()
229 if err != nil {
230 return ""
231 }
232 return strings.TrimSpace(string(out))
233}
234
235func dockerTag(ctx context.Context, src, dst string) error {
236 cmd := exec.CommandContext(ctx, "docker", "tag", src, dst)
237 cmd.Stdout = os.Stdout
238 cmd.Stderr = os.Stderr
239 return cmd.Run()
240}
241
242func dockerPush(ctx context.Context, ref string) error {
243 cmd := exec.CommandContext(ctx, "docker", "push", ref)
244 cmd.Stdout = os.Stdout
245 cmd.Stderr = os.Stderr
246 return cmd.Run()
247}
248
249func dockerImageExists(ctx context.Context, image string) bool {
250 cmd := exec.CommandContext(ctx, "docker", "image", "inspect", image) // #nosec G204
251 cmd.Stdout = nil
252 cmd.Stderr = nil
253 return cmd.Run() == nil
254}
255
256// buildArgPattern matches KEY=VALUE where KEY starts with a letter or underscore.
257var buildArgPattern = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*=.*$`)
258
259func validateBuildArg(arg string) error {
260 if !buildArgPattern.MatchString(arg) {
261 return fmt.Errorf("invalid build arg %q: must match KEY=VALUE where KEY is [a-zA-Z_][a-zA-Z0-9_]*", arg)
262 }
263 return nil
264}