github.com/munnerz/test-infra@v0.0.0-20190108210205-ce3d181dc989/gopherage/pkg/util/util.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 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 util 18 19 import ( 20 "fmt" 21 "golang.org/x/tools/cover" 22 "io" 23 "io/ioutil" 24 "k8s.io/test-infra/gopherage/pkg/cov" 25 "os" 26 ) 27 28 // DumpProfile dumps the profile to the given file destination. 29 // If the destination is "-", it instead writes to stdout. 30 func DumpProfile(destination string, profile []*cover.Profile) error { 31 var output io.Writer 32 if destination == "-" { 33 output = os.Stdout 34 } else { 35 f, err := os.Create(destination) 36 if err != nil { 37 return fmt.Errorf("failed to open %s: %v", destination, err) 38 } 39 defer f.Close() 40 output = f 41 } 42 err := cov.DumpProfile(profile, output) 43 if err != nil { 44 return fmt.Errorf("failed to dump profile: %v", err) 45 } 46 return nil 47 } 48 49 // LoadProfile loads a profile from the given filename. 50 // If the filename is "-", it instead reads from stdin. 51 func LoadProfile(origin string) ([]*cover.Profile, error) { 52 filename := origin 53 if origin == "-" { 54 // Annoyingly, ParseProfiles only accepts a filename, so we have to write the bytes to disk 55 // so it can read them back. 56 // We could probably also just give it /dev/stdin, but that'll break on Windows. 57 tf, err := ioutil.TempFile("", "") 58 if err != nil { 59 return nil, fmt.Errorf("failed to create temp file: %v", err) 60 } 61 defer tf.Close() 62 defer os.Remove(tf.Name()) 63 if _, err := io.Copy(tf, os.Stdin); err != nil { 64 return nil, fmt.Errorf("failed to copy stdin to temp file: %v", err) 65 } 66 filename = tf.Name() 67 } 68 return cover.ParseProfiles(filename) 69 }