github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/sealer/cmd/merge.go (about) 1 // Copyright © 2021 Alibaba Group Holding Ltd. 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 cmd 16 17 import ( 18 "fmt" 19 "strings" 20 21 "github.com/alibaba/sealer/utils/platform" 22 23 "github.com/alibaba/sealer/pkg/image" 24 25 "github.com/spf13/cobra" 26 27 "github.com/alibaba/sealer/logger" 28 ) 29 30 type mergeFlag struct { 31 ImageName string 32 Platform string 33 } 34 35 var mf *mergeFlag 36 37 func getMergeCmd() *cobra.Command { 38 var mergeCmd = &cobra.Command{ 39 Use: "merge", 40 Short: "merge multiple images into one", 41 Long: `sealer merge image1:latest image2:latest image3:latest ......`, 42 Example: ` 43 merge images: 44 sealer merge kubernetes:v1.19.9 mysql:5.7.0 redis:6.0.0 -t new:0.1.0 45 `, 46 Args: cobra.MinimumNArgs(1), 47 RunE: getMergeFunc, 48 } 49 mf = &mergeFlag{} 50 mergeCmd.Flags().StringVarP(&mf.ImageName, "target-image", "t", "", "target image name") 51 mergeCmd.Flags().StringVar(&mf.Platform, "platform", "", "set cloud image platform,if not set,keep same platform with runtime") 52 53 if err := mergeCmd.MarkFlagRequired("target-image"); err != nil { 54 logger.Error("failed to init flag target image: %v", err) 55 } 56 return mergeCmd 57 } 58 59 func getMergeFunc(cmd *cobra.Command, args []string) error { 60 var images []string 61 for _, v := range args { 62 imageName := strings.TrimSpace(v) 63 if imageName == "" { 64 continue 65 } 66 images = append(images, imageName) 67 } 68 targetPlatform, err := platform.GetPlatform(mf.Platform) 69 if err != nil { 70 return err 71 } 72 73 if len(targetPlatform) != 1 { 74 return fmt.Errorf("merge action only do the same plaform at a time") 75 } 76 77 ima := buildRaw(mf.ImageName) 78 if err := image.Merge(ima, images, targetPlatform[0]); err != nil { 79 return err 80 } 81 logger.Info("images %s is merged to %s", strings.Join(images, ","), ima) 82 return nil 83 } 84 85 func buildRaw(name string) string { 86 defaultTag := "latest" 87 i := strings.LastIndexByte(name, ':') 88 if i == -1 { 89 return name + ":" + defaultTag 90 } 91 if i > strings.LastIndexByte(name, '/') { 92 return name 93 } 94 return name + ":" + defaultTag 95 } 96 97 func init() { 98 rootCmd.AddCommand(getMergeCmd()) 99 }