1package cmd
2
3import (
4 "fmt"
5 "os"
6
7 "github.com/bnema/gordon/internal/cli"
8 "github.com/bnema/gordon/internal/cli/handler"
9 "github.com/bnema/gordon/internal/common"
10 "github.com/bnema/gordon/pkg/docker"
11 "github.com/spf13/cobra"
12)
13
14// the push command is used to push a container image to gordon's endpoint
15
16// Pseudo code of the steps for the push command
17
18// 1. Extract the container image as .tar and store it in a temporary directory
19
20// 2. Prepare a payload with the .tar as a byte array, the image name and tag (if any)
21
22// 3. append the payload to the request body with the type "push" and the token
23
24// 4. Send the request to the backend
25
26// 5. If the response is 200, print the success message
27
28func NewPushCommand(a *cli.App) *cobra.Command {
29 var port string
30 var targetDomain string
31
32 // handler.FieldCheck(a)
33
34 pushCmd := &cobra.Command{
35 Use: "push [image:tag]",
36 Short: "Push an image to the server, if no tag is specified, latest is used",
37 Args: cobra.ExactArgs(1),
38 PreRun: func(cmd *cobra.Command, args []string) {
39 if err := handler.FieldCheck(a); err != nil {
40 fmt.Println("Field check failed:", err)
41 os.Exit(1)
42 }
43 },
44 Run: func(cmd *cobra.Command, args []string) {
45 imageName := args[0]
46 fmt.Println("Exporting image:", imageName)
47 // Export the image using Docker client
48 data, err := docker.ExportImageFromEngine(imageName)
49 if err != nil {
50 fmt.Println("Error exporting image:", err)
51 return
52 }
53 fmt.Println("Image exported successfully")
54 // Create a RequestPayload and populate it
55 reqPayload := common.RequestPayload{ // <- TODO : Load RequestPayLoad from cli.App
56 Type: "push",
57 Payload: common.PushPayload{ // <- Same
58 Ports: port,
59 TargetDomain: targetDomain,
60 ImageName: imageName,
61 Data: data,
62 },
63 }
64 fmt.Println("Sending image to backend")
65 // Send the request to the backend
66 resp, err := handler.SendHTTPRequest(a, &reqPayload, "POST", "/push")
67 if err != nil {
68 fmt.Println("Error sending HTTP request:", err)
69 return
70 }
71
72 fmt.Print(string(resp.Body))
73 },
74 }
75
76 // Add flags
77 pushCmd.Flags().StringVarP(&port, "port", "p", "", "Port mapping for the container")
78 pushCmd.Flags().StringVarP(&targetDomain, "target", "t", "", "Target domain for Traefik")
79
80 return pushCmd
81}