github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/cli/trigger.go (about)

     1  package cli
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  	"k8s.io/cli-runtime/pkg/genericclioptions"
    14  
    15  	"github.com/tilt-dev/tilt/internal/analytics"
    16  	analytics2 "github.com/tilt-dev/tilt/internal/engine/analytics"
    17  	"github.com/tilt-dev/tilt/pkg/model"
    18  )
    19  
    20  type triggerCmd struct {
    21  	streams genericclioptions.IOStreams
    22  }
    23  
    24  var _ tiltCmd = &triggerCmd{}
    25  
    26  func newTriggerCmd(streams genericclioptions.IOStreams) *triggerCmd {
    27  	return &triggerCmd{
    28  		streams: streams,
    29  	}
    30  }
    31  
    32  func (t triggerCmd) name() model.TiltSubcommand {
    33  	return "trigger"
    34  }
    35  
    36  func (t triggerCmd) register() *cobra.Command {
    37  	cmd := &cobra.Command{
    38  		Use:   "trigger [RESOURCE_NAME]",
    39  		Short: "Trigger an update for the specified resource",
    40  		Long: `Trigger an update for the specified resource.
    41  
    42  If the resource has Trigger Mode: Manual and has pending changes, this command will cause those pending changes to be applied.
    43  
    44  Otherwise, this command will force a full rebuild.
    45  `,
    46  		Args: cobra.ExactArgs(1),
    47  	}
    48  	addConnectServerFlags(cmd)
    49  	return cmd
    50  }
    51  
    52  func (t triggerCmd) run(ctx context.Context, args []string) error {
    53  	resource := args[0]
    54  
    55  	a := analytics.Get(ctx)
    56  	a.Incr("cmd.trigger", make(analytics2.CmdTags))
    57  	defer a.Flush(time.Second)
    58  
    59  	// TODO(maia): this should probably be the triggerPayload struct, but seems
    60  	//   like a lot of code to move over (to avoid import cycles) for one call.
    61  	payload := []byte(fmt.Sprintf(`{"manifest_names":[%q], "build_reason": %d}`, resource, model.BuildReasonFlagTriggerCLI))
    62  
    63  	r, status := apiPostJson("trigger", payload)
    64  
    65  	b, err := io.ReadAll(r)
    66  	if err != nil {
    67  		return errors.Wrap(err, "error reading response from tilt api")
    68  	}
    69  	_ = r.Close()
    70  
    71  	body := strings.TrimSpace(string(b))
    72  	if status != http.StatusOK {
    73  		return fmt.Errorf("(%d): %s", status, body)
    74  	}
    75  	if len(body) > 0 {
    76  		return errors.New(body)
    77  	}
    78  
    79  	_, _ = fmt.Fprintf(t.streams.Out, "Successfully triggered update for resource: %q\n", resource)
    80  	return nil
    81  }