github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/utils/collector/remote_context.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 collector 16 17 import ( 18 "os" 19 "path/filepath" 20 "strings" 21 22 "github.com/alibaba/sealer/logger" 23 "github.com/cavaliergopher/grab/v3" 24 "github.com/go-git/go-git/v5" 25 "github.com/go-git/go-git/v5/plumbing/transport/ssh" 26 ) 27 28 type webFileCollector struct { 29 } 30 31 func (w webFileCollector) Collect(buildContext, src, savePath string) error { 32 client := grab.NewClient() 33 i := strings.LastIndexByte(src, '/') 34 req, err := grab.NewRequest(filepath.Join(savePath, src[i+1:]), src) 35 if err != nil { 36 return err 37 } 38 //todo add progress message stdout same with docker pull. 39 resp := client.Do(req) 40 if err := resp.Err(); err != nil { 41 return err 42 } 43 return nil 44 } 45 46 func NewWebFileCollector() Collector { 47 return webFileCollector{} 48 } 49 50 type gitCollector struct { 51 } 52 53 func (g gitCollector) Collect(buildContext, src, savePath string) error { 54 co := &git.CloneOptions{ 55 URL: src, 56 RecurseSubmodules: git.DefaultSubmoduleRecursionDepth, 57 Progress: os.Stdout, 58 } 59 60 if strings.HasPrefix(src, "git@") { 61 privateKeyFile := os.Getenv("HOME") + "/.ssh/id_rsa" 62 _, err := os.Stat(privateKeyFile) 63 if err != nil { 64 logger.Warn("read file %s failed %s\n", privateKeyFile, err.Error()) 65 return err 66 } 67 68 publicKeys, err := ssh.NewPublicKeysFromFile("git", privateKeyFile, "") 69 if err != nil { 70 logger.Warn("generate public keys failed: %s\n", err.Error()) 71 return err 72 } 73 co.Auth = publicKeys 74 } 75 _, err := git.PlainClone(savePath, false, co) 76 77 if err != nil { 78 return err 79 } 80 return nil 81 } 82 83 func NewGitCollector() Collector { 84 return gitCollector{} 85 }