|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + |
| 8 | + controllererrors "github.com/docker/buildx/controller/errdefs" |
| 9 | + controllerapi "github.com/docker/buildx/controller/pb" |
| 10 | + "github.com/docker/buildx/monitor/types" |
| 11 | + "github.com/docker/buildx/util/progress" |
| 12 | + "github.com/pkg/errors" |
| 13 | +) |
| 14 | + |
| 15 | +type ReloadCmd struct { |
| 16 | + m types.Monitor |
| 17 | + |
| 18 | + stdout io.WriteCloser |
| 19 | + progress *progress.Printer |
| 20 | + |
| 21 | + options *controllerapi.BuildOptions |
| 22 | + invokeConfig controllerapi.InvokeConfig |
| 23 | +} |
| 24 | + |
| 25 | +func NewReloadCmd(m types.Monitor, stdout io.WriteCloser, progress *progress.Printer, options *controllerapi.BuildOptions, invokeConfig controllerapi.InvokeConfig) types.Command { |
| 26 | + return &ReloadCmd{m, stdout, progress, options, invokeConfig} |
| 27 | +} |
| 28 | + |
| 29 | +func (cm *ReloadCmd) Info() types.CommandInfo { |
| 30 | + return types.CommandInfo{HelpMessage: "reloads the context and build it"} |
| 31 | +} |
| 32 | + |
| 33 | +func (cm *ReloadCmd) Exec(ctx context.Context, args []string) error { |
| 34 | + var bo *controllerapi.BuildOptions |
| 35 | + if ref := cm.m.AttachedSessionID(); ref != "" { |
| 36 | + // Rebuilding an existing session; Restore the build option used for building this session. |
| 37 | + res, err := cm.m.Inspect(ctx, ref) |
| 38 | + if err != nil { |
| 39 | + fmt.Printf("failed to inspect the current build session: %v\n", err) |
| 40 | + } else { |
| 41 | + bo = res.Options |
| 42 | + } |
| 43 | + } else { |
| 44 | + bo = cm.options |
| 45 | + } |
| 46 | + if bo == nil { |
| 47 | + return errors.Errorf("no build option is provided") |
| 48 | + } |
| 49 | + if ref := cm.m.AttachedSessionID(); ref != "" { |
| 50 | + if err := cm.m.Disconnect(ctx, ref); err != nil { |
| 51 | + fmt.Println("disconnect error", err) |
| 52 | + } |
| 53 | + } |
| 54 | + var resultUpdated bool |
| 55 | + cm.progress.Unpause() |
| 56 | + ref, _, err := cm.m.Build(ctx, *bo, nil, cm.progress) // TODO: support stdin, hold build ref |
| 57 | + cm.progress.Pause() |
| 58 | + if err != nil { |
| 59 | + var be *controllererrors.BuildError |
| 60 | + if errors.As(err, &be) { |
| 61 | + ref = be.Ref |
| 62 | + resultUpdated = true |
| 63 | + } else { |
| 64 | + fmt.Printf("failed to reload: %v\n", err) |
| 65 | + } |
| 66 | + } else { |
| 67 | + resultUpdated = true |
| 68 | + } |
| 69 | + cm.m.AttachSession(ref) |
| 70 | + if resultUpdated { |
| 71 | + // rollback the running container with the new result |
| 72 | + id := cm.m.Rollback(ctx, cm.invokeConfig) |
| 73 | + fmt.Fprintf(cm.stdout, "Interactive container was restarted with process %q. Press Ctrl-a-c to switch to the new container\n", id) |
| 74 | + } |
| 75 | + return nil |
| 76 | +} |
0 commit comments