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

     1  package cloud
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"os"
     7  
     8  	"google.golang.org/protobuf/types/known/timestamppb"
     9  	ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
    10  
    11  	"github.com/grpc-ecosystem/grpc-gateway/runtime"
    12  
    13  	"github.com/tilt-dev/tilt/internal/hud/webview"
    14  	"github.com/tilt-dev/tilt/internal/store"
    15  	"github.com/tilt-dev/tilt/pkg/logger"
    16  	proto_webview "github.com/tilt-dev/tilt/pkg/webview"
    17  )
    18  
    19  type Snapshotter struct {
    20  	st     store.RStore
    21  	client ctrlclient.Client
    22  }
    23  
    24  func NewSnapshotter(st store.RStore, client ctrlclient.Client) *Snapshotter {
    25  	return &Snapshotter{
    26  		st:     st,
    27  		client: client,
    28  	}
    29  }
    30  
    31  func (s *Snapshotter) WriteSnapshot(ctx context.Context, path string) {
    32  	view, err := webview.CompleteView(ctx, s.client, s.st)
    33  	if err != nil {
    34  		logger.Get(ctx).Errorf("Fetching snapshot: %v", err)
    35  		return
    36  	}
    37  
    38  	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
    39  	if err != nil {
    40  		logger.Get(ctx).Errorf("Writing snapshot to file: %v", err)
    41  		return
    42  	}
    43  	defer func() {
    44  		_ = f.Close()
    45  	}()
    46  
    47  	snapshot := &proto_webview.Snapshot{
    48  		View:      view,
    49  		CreatedAt: timestamppb.Now(),
    50  	}
    51  
    52  	err = WriteSnapshotTo(ctx, snapshot, f)
    53  	if err != nil {
    54  		logger.Get(ctx).Errorf("Writing snapshot to file: %v", err)
    55  		return
    56  	}
    57  }
    58  
    59  func WriteSnapshotTo(ctx context.Context, snapshot *proto_webview.Snapshot, w io.Writer) error {
    60  	jsEncoder := &runtime.JSONPb{
    61  		OrigName: false,
    62  		Indent:   "  ",
    63  	}
    64  	return jsEncoder.NewEncoder(w).Encode(snapshot)
    65  }