|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net" |
| 9 | + "net/http" |
| 10 | + |
| 11 | + "github.com/spf13/cobra" |
| 12 | +) |
| 13 | + |
| 14 | +func ReadFromVolume(ctx context.Context) *cobra.Command { |
| 15 | + return &cobra.Command{ |
| 16 | + Use: "read-from-volume", |
| 17 | + Short: "Read a file from the extension's volume", |
| 18 | + Args: cobra.ExactArgs(1), |
| 19 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 20 | + content, err := readConfig(ctx, args[0]) |
| 21 | + if err != nil { |
| 22 | + return err |
| 23 | + } |
| 24 | + fmt.Print(content) |
| 25 | + return nil |
| 26 | + }, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func readConfig(ctx context.Context, filename string) (string, error) { |
| 31 | + httpClient := &http.Client{ |
| 32 | + Transport: &http.Transport{ |
| 33 | + DialContext: func(ctx context.Context, _, _ string) (conn net.Conn, err error) { |
| 34 | + return dialVolumeContents(ctx) |
| 35 | + }, |
| 36 | + }, |
| 37 | + } |
| 38 | + |
| 39 | + var content struct { |
| 40 | + Contents string `json:"contents"` |
| 41 | + } |
| 42 | + if err := query(ctx, httpClient, "GET", "/volume-file-content?volumeId=docker-prompts&targetPath="+filename, &content); err != nil { |
| 43 | + return "", err |
| 44 | + } |
| 45 | + |
| 46 | + return content.Contents, nil |
| 47 | +} |
| 48 | + |
| 49 | +func query(ctx context.Context, httpClient *http.Client, method string, endpoint string, v any) error { |
| 50 | + req, err := http.NewRequestWithContext(ctx, method, "http://localhost"+endpoint, nil) |
| 51 | + if err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + req.Header.Set("X-DockerDesktop-Host", "vm.docker.internal") |
| 55 | + |
| 56 | + response, err := httpClient.Do(req) |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + defer response.Body.Close() |
| 61 | + |
| 62 | + buf, err := io.ReadAll(response.Body) |
| 63 | + if err != nil { |
| 64 | + return err |
| 65 | + } |
| 66 | + |
| 67 | + if err := json.Unmarshal(buf, &v); err != nil { |
| 68 | + return err |
| 69 | + } |
| 70 | + return nil |
| 71 | +} |
0 commit comments