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

     1  package cmd
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"github.com/SAP/jenkins-library/pkg/log"
     7  	"github.com/SAP/jenkins-library/pkg/piperenv"
     8  	"github.com/spf13/cobra"
     9  	"io/ioutil"
    10  	"os"
    11  	"path/filepath"
    12  )
    13  
    14  // WritePipelineEnv Serializes the commonPipelineEnvironment JSON to disk
    15  func WritePipelineEnv() *cobra.Command {
    16  	return &cobra.Command{
    17  		Use:   "writePipelineEnv",
    18  		Short: "Serializes the commonPipelineEnvironment JSON to disk",
    19  		PreRun: func(cmd *cobra.Command, args []string) {
    20  			path, _ := os.Getwd()
    21  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    22  			log.RegisterHook(fatalHook)
    23  		},
    24  
    25  		Run: func(cmd *cobra.Command, args []string) {
    26  			err := runWritePipelineEnv()
    27  			if err != nil {
    28  				log.Entry().Fatalf("error when writing common Pipeline environment: %v", err)
    29  			}
    30  		},
    31  	}
    32  }
    33  
    34  func runWritePipelineEnv() error {
    35  	pipelineEnv, ok := os.LookupEnv("PIPER_pipelineEnv")
    36  	inBytes := []byte(pipelineEnv)
    37  	if !ok {
    38  		var err error
    39  		inBytes, err = ioutil.ReadAll(os.Stdin)
    40  		if err != nil {
    41  			return err
    42  		}
    43  	}
    44  	if len(inBytes) == 0 {
    45  		return nil
    46  	}
    47  
    48  	commonPipelineEnv := piperenv.CPEMap{}
    49  	decoder := json.NewDecoder(bytes.NewReader(inBytes))
    50  	decoder.UseNumber()
    51  	err := decoder.Decode(&commonPipelineEnv)
    52  	if err != nil {
    53  		return err
    54  	}
    55  
    56  	rootPath := filepath.Join(GeneralConfig.EnvRootPath, "commonPipelineEnvironment")
    57  	err = commonPipelineEnv.WriteToDisk(rootPath)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	writtenBytes, err := json.MarshalIndent(commonPipelineEnv, "", "\t")
    63  	if err != nil {
    64  		return err
    65  	}
    66  	_, err = os.Stdout.Write(writtenBytes)
    67  	if err != nil {
    68  		return err
    69  	}
    70  	return nil
    71  }