...

Source file src/edge-infra.dev/third_party/gopherage/pkg/util/util.go

Documentation: edge-infra.dev/third_party/gopherage/pkg/util

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

View as plain text