github.com/GoogleContainerTools/kpt@v1.0.0-beta.50.0.20240520170205-c25345ffcbee/commands/alpha/wasm/push/command.go (about)

     1  // Copyright 2022 The kpt Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package push
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"os"
    21  	"path"
    22  
    23  	"github.com/GoogleContainerTools/kpt/internal/docs/generated/wasmdocs"
    24  	"github.com/GoogleContainerTools/kpt/internal/errors"
    25  	"github.com/GoogleContainerTools/kpt/pkg/wasm"
    26  	"github.com/spf13/cobra"
    27  )
    28  
    29  const (
    30  	command = "cmdwasmpush"
    31  )
    32  
    33  func newRunner(ctx context.Context) *runner {
    34  	r := &runner{
    35  		ctx: ctx,
    36  	}
    37  	c := &cobra.Command{
    38  		Use:     "push [LOCAL_PATH] [IMAGE]",
    39  		Short:   wasmdocs.PushShort,
    40  		Long:    wasmdocs.PushShort + "\n" + wasmdocs.PushLong,
    41  		Example: wasmdocs.PushExamples,
    42  		RunE:    r.runE,
    43  	}
    44  	r.Command = c
    45  	return r
    46  }
    47  
    48  func NewCommand(ctx context.Context) *cobra.Command {
    49  	return newRunner(ctx).Command
    50  }
    51  
    52  type runner struct {
    53  	ctx           context.Context
    54  	Command       *cobra.Command
    55  	storageClient *wasm.Client
    56  }
    57  
    58  func (r *runner) runE(_ *cobra.Command, args []string) error {
    59  	const op errors.Op = command + ".runE"
    60  
    61  	if len(args) != 2 {
    62  		return errors.E(op, "2 positional arguments (local wasm file and OCI image) are required")
    63  	}
    64  
    65  	var err error
    66  	if r.storageClient == nil {
    67  		r.storageClient, err = wasm.NewClient(path.Join(os.TempDir(), "kpt"))
    68  		if err != nil {
    69  			return err
    70  		}
    71  	}
    72  
    73  	wasmFile := args[0]
    74  	img := args[1]
    75  
    76  	err = r.storageClient.PushWasm(r.ctx, wasmFile, img)
    77  	if err != nil {
    78  		return err
    79  	}
    80  
    81  	fmt.Printf("image has been pushed to %v\n", img)
    82  	return nil
    83  }