1package cmd
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7
8 "github.com/bnema/gordon/internal/cli"
9 "github.com/bnema/gordon/internal/cli/handler"
10 "github.com/bnema/gordon/internal/common"
11 "github.com/charmbracelet/log"
12 "github.com/spf13/cobra"
13)
14
15func NewPushCommand(a *cli.App) *cobra.Command {
16 var port string
17
18 pushCmd := &cobra.Command{
19 Use: "push [image:tag]",
20 Short: "Push an image to your remote Gordon instance",
21 Args: cobra.ExactArgs(1),
22 PreRun: func(cmd *cobra.Command, args []string) {
23 if err := handler.FieldCheck(a); err != nil {
24 log.Error("Field check failed", "error", err)
25 os.Exit(1)
26 }
27 },
28 Run: func(cmd *cobra.Command, args []string) {
29 imageName := args[0]
30 log.Info("Pushing image", "image", imageName)
31
32 if err := pushImage(a, imageName); err != nil {
33 log.Error("Push failed", "error", err)
34 os.Exit(1)
35 }
36 },
37 }
38
39 pushCmd.Flags().StringVarP(&port, "port", "p", "", "Port mapping for the container (e.g., 8080:80/tcp)")
40
41 return pushCmd
42}
43
44func pushImage(a *cli.App, imageName string) error {
45 if err := handler.ValidateImageName(imageName); err != nil {
46 return fmt.Errorf("invalid image name: %w", err)
47 }
48
49 handler.EnsureImageTag(&imageName)
50
51 reader, actualSize, err := exportDockerImage(imageName)
52 if err != nil {
53 return fmt.Errorf("error exporting image: %w", err)
54 }
55 defer reader.Close()
56
57 log.Info("Image exported successfully", "image", imageName, "size", actualSize)
58
59 reqPayload := common.RequestPayload{
60 Type: "push",
61 Payload: common.PushPayload{
62 ImageName: imageName,
63 Data: reader,
64 },
65 }
66
67 resp, err := handler.SendHTTPRequest(a, &reqPayload, "POST", "/push")
68 if err != nil {
69 return fmt.Errorf("error sending HTTP request: %w", err)
70 }
71
72 var pushResponse common.PushResponse
73 if err := json.Unmarshal(resp.Body, &pushResponse); err != nil {
74 return fmt.Errorf("error parsing response: %w", err)
75 }
76
77 if !pushResponse.Success {
78 return fmt.Errorf("push failed: %s", pushResponse.Message)
79 }
80
81 log.Info("Image pushed successfully", "image", imageName)
82 return nil
83}