github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/core/chaincode/platforms/golang/list.go (about) 1 /* 2 Copyright 2017 - Greg Haskins <gregory.haskins@gmail.com> 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package golang 18 19 import ( 20 "bytes" 21 "errors" 22 "fmt" 23 "os/exec" 24 "strings" 25 "time" 26 ) 27 28 //runProgram non-nil Env, timeout (typically secs or millisecs), program name and args 29 func runProgram(env Env, timeout time.Duration, pgm string, args ...string) ([]byte, error) { 30 if env == nil { 31 return nil, fmt.Errorf("<%s, %v>: nil env provided", pgm, args) 32 } 33 var stdOut bytes.Buffer 34 var stdErr bytes.Buffer 35 36 cmd := exec.Command(pgm, args...) 37 cmd.Env = flattenEnv(env) 38 cmd.Stdout = &stdOut 39 cmd.Stderr = &stdErr 40 err := cmd.Start() 41 42 // Create a go routine that will wait for the command to finish 43 done := make(chan error, 1) 44 go func() { 45 done <- cmd.Wait() 46 }() 47 48 select { 49 case <-time.After(timeout): 50 if err = cmd.Process.Kill(); err != nil { 51 return nil, fmt.Errorf("<%s, %v>: failed to kill: %s", pgm, args, err) 52 } else { 53 return nil, errors.New(fmt.Sprintf("<%s, %v>: timeout(%d msecs)", pgm, args, timeout/time.Millisecond)) 54 } 55 case err = <-done: 56 if err != nil { 57 return nil, fmt.Errorf("<%s, %v>: failed with error: \"%s\"\n%s", pgm, args, err, string(stdErr.Bytes())) 58 } 59 60 return stdOut.Bytes(), nil 61 } 62 } 63 64 // Logic inspired by: https://dave.cheney.net/2014/09/14/go-list-your-swiss-army-knife 65 func list(env Env, template, pkg string) ([]string, error) { 66 if env == nil { 67 env = getEnv() 68 } 69 70 lst, err := runProgram(env, 60*time.Second, "go", "list", "-f", template, pkg) 71 if err != nil { 72 return nil, err 73 } 74 75 return strings.Split(strings.Trim(string(lst), "\n"), "\n"), nil 76 } 77 78 func listDeps(env Env, pkg string) ([]string, error) { 79 return list(env, "{{ join .Deps \"\\n\"}}", pkg) 80 } 81 82 func listImports(env Env, pkg string) ([]string, error) { 83 return list(env, "{{ join .Imports \"\\n\"}}", pkg) 84 }