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

     1  // Code generated by piper's step-generator. DO NOT EDIT.
     2  
     3  package cmd
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/SAP/jenkins-library/pkg/config"
    11  	"github.com/SAP/jenkins-library/pkg/log"
    12  	"github.com/SAP/jenkins-library/pkg/splunk"
    13  	"github.com/SAP/jenkins-library/pkg/telemetry"
    14  	"github.com/SAP/jenkins-library/pkg/validation"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type nexusUploadOptions struct {
    19  	Version            string `json:"version,omitempty" validate:"possible-values=nexus2 nexus3"`
    20  	Format             string `json:"format,omitempty" validate:"possible-values=maven npm"`
    21  	Url                string `json:"url,omitempty"`
    22  	MavenRepository    string `json:"mavenRepository,omitempty"`
    23  	NpmRepository      string `json:"npmRepository,omitempty"`
    24  	GroupID            string `json:"groupId,omitempty"`
    25  	ArtifactID         string `json:"artifactId,omitempty"`
    26  	GlobalSettingsFile string `json:"globalSettingsFile,omitempty"`
    27  	M2Path             string `json:"m2Path,omitempty"`
    28  	Username           string `json:"username,omitempty"`
    29  	Password           string `json:"password,omitempty"`
    30  }
    31  
    32  // NexusUploadCommand Upload artifacts to Nexus Repository Manager
    33  func NexusUploadCommand() *cobra.Command {
    34  	const STEP_NAME = "nexusUpload"
    35  
    36  	metadata := nexusUploadMetadata()
    37  	var stepConfig nexusUploadOptions
    38  	var startTime time.Time
    39  	var logCollector *log.CollectorHook
    40  	var splunkClient *splunk.Splunk
    41  	telemetryClient := &telemetry.Telemetry{}
    42  
    43  	var createNexusUploadCmd = &cobra.Command{
    44  		Use:   STEP_NAME,
    45  		Short: "Upload artifacts to Nexus Repository Manager",
    46  		Long: `Upload build artifacts to a Nexus Repository Manager.
    47  
    48  Supports MTA, npm and (multi-module) Maven projects.
    49  MTA files will be uploaded to a Maven repository.
    50  
    51  The uploaded file-type depends on your project structure and step configuration.
    52  To upload Maven projects, you need a pom.xml in the project root and set the mavenRepository option.
    53  To upload MTA projects, you need a mta.yaml in the project root and set the mavenRepository option.
    54  To upload npm projects, you need a package.json in the project root and set the npmRepository option.
    55  
    56  If the 'format' option is set, the 'URL' can contain the full path including the repository ID. Providing the 'npmRepository' or the 'mavenRepository' parameter(s) is not necessary.
    57  
    58  npm:
    59  Publishing npm projects makes use of npm's "publish" command.
    60  It requires a "package.json" file in the project's root directory which has "version" set and is not delared as "private".
    61  To find out what will be published, run "npm publish --dry-run" in the project's root folder.
    62  It will use your gitignore file to exclude the mached files from publishing.
    63  Note: npm's gitignore parser might yield different results from your git client, to ignore a "foo" directory globally use the glob pattern "**/foo".
    64  
    65  If an image for mavenExecute is configured, and npm packages are to be published, the image must have npm installed.`,
    66  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    67  			startTime = time.Now()
    68  			log.SetStepName(STEP_NAME)
    69  			log.SetVerbose(GeneralConfig.Verbose)
    70  
    71  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    72  
    73  			path, _ := os.Getwd()
    74  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    75  			log.RegisterHook(fatalHook)
    76  
    77  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    78  			if err != nil {
    79  				log.SetErrorCategory(log.ErrorConfiguration)
    80  				return err
    81  			}
    82  			log.RegisterSecret(stepConfig.Username)
    83  			log.RegisterSecret(stepConfig.Password)
    84  
    85  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    86  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    87  				log.RegisterHook(&sentryHook)
    88  			}
    89  
    90  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
    91  				splunkClient = &splunk.Splunk{}
    92  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    93  				log.RegisterHook(logCollector)
    94  			}
    95  
    96  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    97  			if err != nil {
    98  				return err
    99  			}
   100  			if err = validation.ValidateStruct(stepConfig); err != nil {
   101  				log.SetErrorCategory(log.ErrorConfiguration)
   102  				return err
   103  			}
   104  
   105  			return nil
   106  		},
   107  		Run: func(_ *cobra.Command, _ []string) {
   108  			stepTelemetryData := telemetry.CustomData{}
   109  			stepTelemetryData.ErrorCode = "1"
   110  			handler := func() {
   111  				config.RemoveVaultSecretFiles()
   112  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   113  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   114  				stepTelemetryData.PiperCommitHash = GitCommit
   115  				telemetryClient.SetData(&stepTelemetryData)
   116  				telemetryClient.Send()
   117  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   118  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   119  				}
   120  			}
   121  			log.DeferExitHandler(handler)
   122  			defer handler()
   123  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   124  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   125  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   126  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   127  					GeneralConfig.HookConfig.SplunkConfig.Token,
   128  					GeneralConfig.HookConfig.SplunkConfig.Index,
   129  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   130  			}
   131  			nexusUpload(stepConfig, &stepTelemetryData)
   132  			stepTelemetryData.ErrorCode = "0"
   133  			log.Entry().Info("SUCCESS")
   134  		},
   135  	}
   136  
   137  	addNexusUploadFlags(createNexusUploadCmd, &stepConfig)
   138  	return createNexusUploadCmd
   139  }
   140  
   141  func addNexusUploadFlags(cmd *cobra.Command, stepConfig *nexusUploadOptions) {
   142  	cmd.Flags().StringVar(&stepConfig.Version, "version", `nexus3`, "The Nexus Repository Manager version. Currently supported are 'nexus2' and 'nexus3'.")
   143  	cmd.Flags().StringVar(&stepConfig.Format, "format", `maven`, "The format/registry type. Currently supported are 'maven' and 'npm'.")
   144  	cmd.Flags().StringVar(&stepConfig.Url, "url", os.Getenv("PIPER_url"), "URL of the nexus. The scheme part of the URL will not be considered, because only http is supported. If the 'format' option is set, the 'URL' can contain the full path including the repository ID and providing the 'npmRepository' or the 'mavenRepository' parameter(s) is not necessary.")
   145  	cmd.Flags().StringVar(&stepConfig.MavenRepository, "mavenRepository", os.Getenv("PIPER_mavenRepository"), "Name of the nexus repository for Maven and MTA deployments. If this is not provided, Maven and MTA deployment is implicitly disabled.")
   146  	cmd.Flags().StringVar(&stepConfig.NpmRepository, "npmRepository", os.Getenv("PIPER_npmRepository"), "Name of the nexus repository for npm deployments. If this is not provided, npm deployment is implicitly disabled.")
   147  	cmd.Flags().StringVar(&stepConfig.GroupID, "groupId", os.Getenv("PIPER_groupId"), "Group ID of the artifacts. Only used in MTA projects, ignored for Maven.")
   148  	cmd.Flags().StringVar(&stepConfig.ArtifactID, "artifactId", os.Getenv("PIPER_artifactId"), "The artifact ID used for both the .mtar and mta.yaml files deployed for MTA projects, ignored for Maven.")
   149  	cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
   150  	cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "The path to the local .m2 directory, only used for Maven projects.")
   151  	cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "Username for accessing the Nexus endpoint.")
   152  	cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password for accessing the Nexus endpoint.")
   153  
   154  	cmd.MarkFlagRequired("url")
   155  }
   156  
   157  // retrieve step metadata
   158  func nexusUploadMetadata() config.StepData {
   159  	var theMetaData = config.StepData{
   160  		Metadata: config.StepMetadata{
   161  			Name:        "nexusUpload",
   162  			Aliases:     []config.Alias{{Name: "mavenExecute", Deprecated: false}},
   163  			Description: "Upload artifacts to Nexus Repository Manager",
   164  		},
   165  		Spec: config.StepSpec{
   166  			Inputs: config.StepInputs{
   167  				Secrets: []config.StepSecrets{
   168  					{Name: "nexusCredentialsId", Description: "Jenkins 'Username with password' credentials ID containing the technical username/password credential for accessing the nexus endpoint.", Type: "jenkins", Aliases: []config.Alias{{Name: "nexus/credentialsId", Deprecated: false}}},
   169  				},
   170  				Resources: []config.StepResources{
   171  					{Name: "buildDescriptor", Type: "stash"},
   172  					{Name: "buildResult", Type: "stash"},
   173  				},
   174  				Parameters: []config.StepParameters{
   175  					{
   176  						Name:        "version",
   177  						ResourceRef: []config.ResourceReference{},
   178  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   179  						Type:        "string",
   180  						Mandatory:   false,
   181  						Aliases:     []config.Alias{{Name: "nexus/version"}},
   182  						Default:     `nexus3`,
   183  					},
   184  					{
   185  						Name: "format",
   186  						ResourceRef: []config.ResourceReference{
   187  							{
   188  								Name:  "commonPipelineEnvironment",
   189  								Param: "custom/repositoryFormat",
   190  							},
   191  						},
   192  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   193  						Type:      "string",
   194  						Mandatory: false,
   195  						Aliases:   []config.Alias{},
   196  						Default:   `maven`,
   197  					},
   198  					{
   199  						Name: "url",
   200  						ResourceRef: []config.ResourceReference{
   201  							{
   202  								Name:  "commonPipelineEnvironment",
   203  								Param: "custom/repositoryUrl",
   204  							},
   205  						},
   206  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   207  						Type:      "string",
   208  						Mandatory: true,
   209  						Aliases:   []config.Alias{{Name: "nexus/url"}},
   210  						Default:   os.Getenv("PIPER_url"),
   211  					},
   212  					{
   213  						Name:        "mavenRepository",
   214  						ResourceRef: []config.ResourceReference{},
   215  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   216  						Type:        "string",
   217  						Mandatory:   false,
   218  						Aliases:     []config.Alias{{Name: "nexus/mavenRepository"}, {Name: "nexus/repository", Deprecated: true}},
   219  						Default:     os.Getenv("PIPER_mavenRepository"),
   220  					},
   221  					{
   222  						Name:        "npmRepository",
   223  						ResourceRef: []config.ResourceReference{},
   224  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   225  						Type:        "string",
   226  						Mandatory:   false,
   227  						Aliases:     []config.Alias{{Name: "nexus/npmRepository"}},
   228  						Default:     os.Getenv("PIPER_npmRepository"),
   229  					},
   230  					{
   231  						Name:        "groupId",
   232  						ResourceRef: []config.ResourceReference{},
   233  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   234  						Type:        "string",
   235  						Mandatory:   false,
   236  						Aliases:     []config.Alias{{Name: "nexus/groupId"}},
   237  						Default:     os.Getenv("PIPER_groupId"),
   238  					},
   239  					{
   240  						Name:        "artifactId",
   241  						ResourceRef: []config.ResourceReference{},
   242  						Scope:       []string{"PARAMETERS"},
   243  						Type:        "string",
   244  						Mandatory:   false,
   245  						Aliases:     []config.Alias{},
   246  						Default:     os.Getenv("PIPER_artifactId"),
   247  					},
   248  					{
   249  						Name:        "globalSettingsFile",
   250  						ResourceRef: []config.ResourceReference{},
   251  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   252  						Type:        "string",
   253  						Mandatory:   false,
   254  						Aliases:     []config.Alias{{Name: "maven/globalSettingsFile"}},
   255  						Default:     os.Getenv("PIPER_globalSettingsFile"),
   256  					},
   257  					{
   258  						Name:        "m2Path",
   259  						ResourceRef: []config.ResourceReference{},
   260  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   261  						Type:        "string",
   262  						Mandatory:   false,
   263  						Aliases:     []config.Alias{{Name: "maven/m2Path"}},
   264  						Default:     os.Getenv("PIPER_m2Path"),
   265  					},
   266  					{
   267  						Name: "username",
   268  						ResourceRef: []config.ResourceReference{
   269  							{
   270  								Name:  "nexusCredentialsId",
   271  								Param: "username",
   272  								Type:  "secret",
   273  							},
   274  
   275  							{
   276  								Name:  "commonPipelineEnvironment",
   277  								Param: "custom/repositoryUsername",
   278  							},
   279  						},
   280  						Scope:     []string{"PARAMETERS"},
   281  						Type:      "string",
   282  						Mandatory: false,
   283  						Aliases:   []config.Alias{},
   284  						Default:   os.Getenv("PIPER_username"),
   285  					},
   286  					{
   287  						Name: "password",
   288  						ResourceRef: []config.ResourceReference{
   289  							{
   290  								Name:  "nexusCredentialsId",
   291  								Param: "password",
   292  								Type:  "secret",
   293  							},
   294  
   295  							{
   296  								Name:  "commonPipelineEnvironment",
   297  								Param: "custom/repositoryPassword",
   298  							},
   299  						},
   300  						Scope:     []string{"PARAMETERS"},
   301  						Type:      "string",
   302  						Mandatory: false,
   303  						Aliases:   []config.Alias{},
   304  						Default:   os.Getenv("PIPER_password"),
   305  					},
   306  				},
   307  			},
   308  			Containers: []config.Container{
   309  				{Name: "mvn-npm", Image: "devxci/mbtci-java11-node14"},
   310  			},
   311  		},
   312  	}
   313  	return theMetaData
   314  }