github.com/xgoffin/jenkins-library@v1.154.0/cmd/getDefaults.go (about)

     1  package cmd
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  
     9  	"github.com/SAP/jenkins-library/pkg/config"
    10  	"github.com/SAP/jenkins-library/pkg/log"
    11  	"github.com/SAP/jenkins-library/pkg/piperutils"
    12  	"github.com/pkg/errors"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  type defaultsCommandOptions struct {
    17  	output        string //output format of default configs, currently only YAML
    18  	outputFile    string //if set: path to file where the output should be written to
    19  	defaultsFiles []string
    20  	openFile      func(s string, t map[string]string) (io.ReadCloser, error)
    21  }
    22  
    23  var defaultsOptions defaultsCommandOptions
    24  
    25  type getDefaultsUtils interface {
    26  	FileExists(filename string) (bool, error)
    27  	DirExists(path string) (bool, error)
    28  	FileWrite(path string, content []byte, perm os.FileMode) error
    29  }
    30  
    31  type getDefaultsUtilsBundle struct {
    32  	*piperutils.Files
    33  }
    34  
    35  func newGetDefaultsUtilsUtils() getDefaultsUtils {
    36  	utils := getDefaultsUtilsBundle{
    37  		Files: &piperutils.Files{},
    38  	}
    39  	return &utils
    40  }
    41  
    42  // DefaultsCommand is the entry command for loading the configuration of a pipeline step
    43  func DefaultsCommand() *cobra.Command {
    44  
    45  	defaultsOptions.openFile = config.OpenPiperFile
    46  	log.Entry().Info(defaultsOptions)
    47  	var createDefaultsCmd = &cobra.Command{
    48  		Use:   "getDefaults",
    49  		Short: "Retrieves multiple default configurations and outputs them embedded into a JSON object.",
    50  		PreRun: func(cmd *cobra.Command, args []string) {
    51  			path, _ := os.Getwd()
    52  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    53  			log.RegisterHook(fatalHook)
    54  			initStageName(false)
    55  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    56  		},
    57  		Run: func(cmd *cobra.Command, _ []string) {
    58  			utils := newGetDefaultsUtilsUtils()
    59  			_, err := generateDefaults(utils)
    60  			if err != nil {
    61  				log.SetErrorCategory(log.ErrorConfiguration)
    62  				log.Entry().WithError(err).Fatal("failed to retrieve default configurations")
    63  			}
    64  		},
    65  	}
    66  
    67  	addDefaultsFlags(createDefaultsCmd)
    68  	return createDefaultsCmd
    69  }
    70  
    71  func getDefaults() ([]map[string]string, error) {
    72  
    73  	var yamlDefaults []map[string]string
    74  
    75  	for _, f := range defaultsOptions.defaultsFiles {
    76  		fc, err := defaultsOptions.openFile(f, GeneralConfig.GitHubAccessTokens)
    77  		if err != nil {
    78  			return yamlDefaults, errors.Wrapf(err, "defaults: retrieving defaults file failed: '%v'", f)
    79  		}
    80  		if err == nil {
    81  			var c config.Config
    82  			c.ReadConfig(fc)
    83  
    84  			yaml, err := config.GetYAML(c)
    85  			if err != nil {
    86  				return yamlDefaults, errors.Wrapf(err, "defaults: could not marshal YAML default file: '%v", f)
    87  			}
    88  
    89  			yamlDefaults = append(yamlDefaults, map[string]string{"content": yaml, "filepath": f})
    90  		}
    91  	}
    92  
    93  	return yamlDefaults, nil
    94  }
    95  
    96  func generateDefaults(utils getDefaultsUtils) ([]byte, error) {
    97  
    98  	var jsonOutput []byte
    99  
   100  	yamlDefaults, err := getDefaults()
   101  	if err != nil {
   102  		return jsonOutput, err
   103  	}
   104  
   105  	if len(yamlDefaults) > 1 {
   106  		jsonOutput, err = json.Marshal(yamlDefaults)
   107  	} else {
   108  		jsonOutput, err = json.Marshal(yamlDefaults[0])
   109  	}
   110  
   111  	if err != nil {
   112  		return jsonOutput, errors.Wrapf(err, "defaults: could not embed YAML defaults into JSON")
   113  	}
   114  
   115  	if len(defaultsOptions.outputFile) > 0 {
   116  		err := utils.FileWrite(defaultsOptions.outputFile, []byte(jsonOutput), 0666)
   117  		if err != nil {
   118  			return jsonOutput, fmt.Errorf("failed to write output file %v: %w", configOptions.outputFile, err)
   119  		}
   120  		return jsonOutput, nil
   121  	}
   122  	fmt.Println(string(jsonOutput))
   123  
   124  	return jsonOutput, nil
   125  }
   126  
   127  func addDefaultsFlags(cmd *cobra.Command) {
   128  
   129  	cmd.Flags().StringVar(&defaultsOptions.output, "output", "yaml", "Defines the format of the configs embedded into a JSON object")
   130  	cmd.Flags().StringVar(&defaultsOptions.outputFile, "outputFile", "", "Defines the output filename")
   131  	cmd.Flags().StringArrayVar(&defaultsOptions.defaultsFiles, "defaultsFile", []string{}, "Defines the input defaults file(s)")
   132  
   133  	cmd.MarkFlagRequired("defaultsFile")
   134  }