github.com/munnerz/test-infra@v0.0.0-20190108210205-ce3d181dc989/gopherage/cmd/aggregate/aggregate.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 aggregate
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  
    23  	"github.com/spf13/cobra"
    24  	"golang.org/x/tools/cover"
    25  	"k8s.io/test-infra/gopherage/pkg/cov"
    26  	"k8s.io/test-infra/gopherage/pkg/util"
    27  )
    28  
    29  type flags struct {
    30  	OutputFile string
    31  }
    32  
    33  // MakeCommand returns an `aggregate` command.
    34  func MakeCommand() *cobra.Command {
    35  	flags := &flags{}
    36  	cmd := &cobra.Command{
    37  		Use:   "aggregate [files...]",
    38  		Short: "Aggregates multiple Go coverage files.",
    39  		Long: `Given multiple Go coverage files from identical binaries recorded in
    40  "count" or "atomic" mode, produces a new Go coverage file in the same mode
    41  that counts how many of those coverage profiles hit a block at least once.`,
    42  		Run: func(cmd *cobra.Command, args []string) {
    43  			run(flags, cmd, args)
    44  		},
    45  	}
    46  	cmd.Flags().StringVarP(&flags.OutputFile, "output", "o", "-", "output file")
    47  	return cmd
    48  }
    49  
    50  func run(flags *flags, cmd *cobra.Command, args []string) {
    51  	if len(args) == 0 {
    52  		fmt.Println("Expected at least one file.")
    53  		cmd.Usage()
    54  		os.Exit(2)
    55  	}
    56  
    57  	profiles := make([][]*cover.Profile, 0, len(args))
    58  	for _, path := range args {
    59  		profile, err := util.LoadProfile(path)
    60  		if err != nil {
    61  			fmt.Fprintf(os.Stderr, "failed to open %s: %v", path, err)
    62  			os.Exit(1)
    63  		}
    64  		profiles = append(profiles, profile)
    65  	}
    66  
    67  	aggregated, err := cov.AggregateProfiles(profiles)
    68  	if err != nil {
    69  		fmt.Fprintf(os.Stderr, "failed to aggregate files: %v", err)
    70  		os.Exit(1)
    71  	}
    72  
    73  	if err := util.DumpProfile(flags.OutputFile, aggregated); err != nil {
    74  		fmt.Fprintln(os.Stderr, err)
    75  		os.Exit(1)
    76  	}
    77  }