...

Source file src/edge-infra.dev/third_party/gopherage/cmd/metadata/metadata.go

Documentation: edge-infra.dev/third_party/gopherage/cmd/metadata

     1  /*
     2  Copyright 2021 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 metadata
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  	"os"
    25  	"os/exec"
    26  	"strings"
    27  
    28  	"github.com/spf13/cobra"
    29  )
    30  
    31  const (
    32  	// From https://github.com/kubernetes/test-infra/blob/master/prow/jobs.md#job-environment-variables
    33  	repo_owner = "REPO_OWNER"
    34  )
    35  
    36  type flags struct {
    37  	outputFile    string
    38  	host          string
    39  	project       string
    40  	commitID      string
    41  	ref           string
    42  	workspaceRoot string
    43  }
    44  
    45  type CoverageMetadata struct {
    46  	Host     string `json:"host"`
    47  	Project  string `json:"project"`
    48  	Root     string `json:"workspace_root"`
    49  	Ref      string `json:"ref"`
    50  	CommitID string `json:"commit_id"`
    51  }
    52  
    53  // MakeCommand returns a `junit` command.
    54  func MakeCommand() *cobra.Command {
    55  	flags := &flags{}
    56  	cmd := &cobra.Command{
    57  		Use:   "metadata [...fields]",
    58  		Short: "Produce json file containing metadata about coverage collection.",
    59  		Long:  `Builds a json file containing information about the repo .`,
    60  		Run: func(cmd *cobra.Command, args []string) {
    61  			run(flags, cmd, args)
    62  		},
    63  	}
    64  	cmd.Flags().StringVarP(&flags.outputFile, "output", "o", "-", "output file")
    65  	cmd.Flags().StringVarP(&flags.host, "host", "", "", "Name of repo host")
    66  	cmd.Flags().StringVarP(&flags.project, "project", "p", "", "Project name")
    67  	cmd.Flags().StringVarP(&flags.commitID, "commit", "c", "", "Current Commit Hash (git rev-parse HEAD)")
    68  	cmd.Flags().StringVarP(&flags.ref, "ref", "r", "", "Current branch ref (git branch --show-current).")
    69  	cmd.Flags().StringVarP(&flags.workspaceRoot, "root", "w", "", "path to root of repo")
    70  	return cmd
    71  }
    72  
    73  func gitCommand(args ...string) (string, error) {
    74  	cmd := exec.Command("git", args...)
    75  	var out bytes.Buffer
    76  	cmd.Stdout = &out
    77  
    78  	err := cmd.Run()
    79  	if err != nil {
    80  		return "", err
    81  	}
    82  	return strings.TrimSuffix(out.String(), "\n"), nil
    83  }
    84  
    85  func run(flags *flags, cmd *cobra.Command, args []string) {
    86  	if flags.project == "" {
    87  		project := os.Getenv(repo_owner)
    88  		if project == "" {
    89  			fmt.Fprintf(os.Stdout, "Failed to collect project from ENV: (%s) not found", repo_owner)
    90  			cmd.Usage()
    91  			os.Exit(1)
    92  		}
    93  		flags.project = project
    94  	}
    95  
    96  	if flags.commitID == "" {
    97  		commit, err := gitCommand("rev-parse", "HEAD")
    98  		if err != nil {
    99  			fmt.Fprintf(os.Stderr, "Failed to fetch Commit Hash from within covered repo: %v.", err)
   100  			os.Exit(1)
   101  		}
   102  		flags.commitID = commit
   103  	}
   104  
   105  	if flags.ref == "" {
   106  		ref, err := gitCommand("branch", "--show-current")
   107  
   108  		if err != nil {
   109  			fmt.Fprintf(os.Stderr, "Failed to fetch ref from within covered repo: %v. Defaulting to HEAD", err)
   110  			ref = "HEAD"
   111  		}
   112  		flags.ref = ref
   113  	}
   114  
   115  	metadata := &CoverageMetadata{
   116  		Host:     flags.host,
   117  		Project:  flags.project,
   118  		Root:     flags.workspaceRoot,
   119  		Ref:      flags.ref,
   120  		CommitID: flags.commitID,
   121  	}
   122  
   123  	j, err := json.Marshal(metadata)
   124  
   125  	if err != nil {
   126  		fmt.Fprintf(os.Stderr, "Failed to build json: %v.", err)
   127  		os.Exit(1)
   128  	}
   129  
   130  	var file io.WriteCloser
   131  	if flags.outputFile == "-" {
   132  		file = os.Stdout
   133  	} else {
   134  		file, err = os.Create(flags.outputFile)
   135  		if err != nil {
   136  			fmt.Fprintf(os.Stderr, "Failed to create file: %v.", err)
   137  			os.Exit(1)
   138  		}
   139  	}
   140  	if _, err := file.Write(j); err != nil {
   141  		fmt.Fprintf(os.Stderr, "Failed to write json: %v.", err)
   142  		os.Exit(1)
   143  	}
   144  	file.Close()
   145  }
   146  

View as plain text