github.com/SAP/jenkins-library@v1.362.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 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
    91  				splunkClient = &splunk.Splunk{}
    92  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    93  				log.RegisterHook(logCollector)
    94  			}
    95  
    96  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    97  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    98  			}
    99  
   100  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   101  			if err != nil {
   102  				return err
   103  			}
   104  			if err = validation.ValidateStruct(stepConfig); err != nil {
   105  				log.SetErrorCategory(log.ErrorConfiguration)
   106  				return err
   107  			}
   108  
   109  			return nil
   110  		},
   111  		Run: func(_ *cobra.Command, _ []string) {
   112  			stepTelemetryData := telemetry.CustomData{}
   113  			stepTelemetryData.ErrorCode = "1"
   114  			handler := func() {
   115  				config.RemoveVaultSecretFiles()
   116  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   117  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   118  				stepTelemetryData.PiperCommitHash = GitCommit
   119  				telemetryClient.SetData(&stepTelemetryData)
   120  				telemetryClient.Send()
   121  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   122  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   123  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   124  						GeneralConfig.HookConfig.SplunkConfig.Token,
   125  						GeneralConfig.HookConfig.SplunkConfig.Index,
   126  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   127  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   128  				}
   129  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   130  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   131  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   132  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   133  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   134  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   135  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   136  				}
   137  			}
   138  			log.DeferExitHandler(handler)
   139  			defer handler()
   140  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   141  			nexusUpload(stepConfig, &stepTelemetryData)
   142  			stepTelemetryData.ErrorCode = "0"
   143  			log.Entry().Info("SUCCESS")
   144  		},
   145  	}
   146  
   147  	addNexusUploadFlags(createNexusUploadCmd, &stepConfig)
   148  	return createNexusUploadCmd
   149  }
   150  
   151  func addNexusUploadFlags(cmd *cobra.Command, stepConfig *nexusUploadOptions) {
   152  	cmd.Flags().StringVar(&stepConfig.Version, "version", `nexus3`, "The Nexus Repository Manager version. Currently supported are 'nexus2' and 'nexus3'.")
   153  	cmd.Flags().StringVar(&stepConfig.Format, "format", `maven`, "The format/registry type. Currently supported are 'maven' and 'npm'.")
   154  	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.")
   155  	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.")
   156  	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.")
   157  	cmd.Flags().StringVar(&stepConfig.GroupID, "groupId", os.Getenv("PIPER_groupId"), "Group ID of the artifacts. Only used in MTA projects, ignored for Maven.")
   158  	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.")
   159  	cmd.Flags().StringVar(&stepConfig.GlobalSettingsFile, "globalSettingsFile", os.Getenv("PIPER_globalSettingsFile"), "Path to the mvn settings file that should be used as global settings file.")
   160  	cmd.Flags().StringVar(&stepConfig.M2Path, "m2Path", os.Getenv("PIPER_m2Path"), "The path to the local .m2 directory, only used for Maven projects.")
   161  	cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "Username for accessing the Nexus endpoint.")
   162  	cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password for accessing the Nexus endpoint.")
   163  
   164  	cmd.MarkFlagRequired("url")
   165  }
   166  
   167  // retrieve step metadata
   168  func nexusUploadMetadata() config.StepData {
   169  	var theMetaData = config.StepData{
   170  		Metadata: config.StepMetadata{
   171  			Name:        "nexusUpload",
   172  			Aliases:     []config.Alias{{Name: "mavenExecute", Deprecated: false}},
   173  			Description: "Upload artifacts to Nexus Repository Manager",
   174  		},
   175  		Spec: config.StepSpec{
   176  			Inputs: config.StepInputs{
   177  				Secrets: []config.StepSecrets{
   178  					{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}}},
   179  				},
   180  				Resources: []config.StepResources{
   181  					{Name: "buildDescriptor", Type: "stash"},
   182  					{Name: "buildResult", Type: "stash"},
   183  				},
   184  				Parameters: []config.StepParameters{
   185  					{
   186  						Name:        "version",
   187  						ResourceRef: []config.ResourceReference{},
   188  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   189  						Type:        "string",
   190  						Mandatory:   false,
   191  						Aliases:     []config.Alias{{Name: "nexus/version"}},
   192  						Default:     `nexus3`,
   193  					},
   194  					{
   195  						Name: "format",
   196  						ResourceRef: []config.ResourceReference{
   197  							{
   198  								Name:  "commonPipelineEnvironment",
   199  								Param: "custom/repositoryFormat",
   200  							},
   201  						},
   202  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   203  						Type:      "string",
   204  						Mandatory: false,
   205  						Aliases:   []config.Alias{},
   206  						Default:   `maven`,
   207  					},
   208  					{
   209  						Name: "url",
   210  						ResourceRef: []config.ResourceReference{
   211  							{
   212  								Name:  "commonPipelineEnvironment",
   213  								Param: "custom/repositoryUrl",
   214  							},
   215  						},
   216  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   217  						Type:      "string",
   218  						Mandatory: true,
   219  						Aliases:   []config.Alias{{Name: "nexus/url"}},
   220  						Default:   os.Getenv("PIPER_url"),
   221  					},
   222  					{
   223  						Name:        "mavenRepository",
   224  						ResourceRef: []config.ResourceReference{},
   225  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   226  						Type:        "string",
   227  						Mandatory:   false,
   228  						Aliases:     []config.Alias{{Name: "nexus/mavenRepository"}, {Name: "nexus/repository", Deprecated: true}},
   229  						Default:     os.Getenv("PIPER_mavenRepository"),
   230  					},
   231  					{
   232  						Name:        "npmRepository",
   233  						ResourceRef: []config.ResourceReference{},
   234  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   235  						Type:        "string",
   236  						Mandatory:   false,
   237  						Aliases:     []config.Alias{{Name: "nexus/npmRepository"}},
   238  						Default:     os.Getenv("PIPER_npmRepository"),
   239  					},
   240  					{
   241  						Name:        "groupId",
   242  						ResourceRef: []config.ResourceReference{},
   243  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   244  						Type:        "string",
   245  						Mandatory:   false,
   246  						Aliases:     []config.Alias{{Name: "nexus/groupId"}},
   247  						Default:     os.Getenv("PIPER_groupId"),
   248  					},
   249  					{
   250  						Name:        "artifactId",
   251  						ResourceRef: []config.ResourceReference{},
   252  						Scope:       []string{"PARAMETERS"},
   253  						Type:        "string",
   254  						Mandatory:   false,
   255  						Aliases:     []config.Alias{},
   256  						Default:     os.Getenv("PIPER_artifactId"),
   257  					},
   258  					{
   259  						Name:        "globalSettingsFile",
   260  						ResourceRef: []config.ResourceReference{},
   261  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   262  						Type:        "string",
   263  						Mandatory:   false,
   264  						Aliases:     []config.Alias{{Name: "maven/globalSettingsFile"}},
   265  						Default:     os.Getenv("PIPER_globalSettingsFile"),
   266  					},
   267  					{
   268  						Name:        "m2Path",
   269  						ResourceRef: []config.ResourceReference{},
   270  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   271  						Type:        "string",
   272  						Mandatory:   false,
   273  						Aliases:     []config.Alias{{Name: "maven/m2Path"}},
   274  						Default:     os.Getenv("PIPER_m2Path"),
   275  					},
   276  					{
   277  						Name: "username",
   278  						ResourceRef: []config.ResourceReference{
   279  							{
   280  								Name:  "nexusCredentialsId",
   281  								Param: "username",
   282  								Type:  "secret",
   283  							},
   284  
   285  							{
   286  								Name:  "commonPipelineEnvironment",
   287  								Param: "custom/repositoryUsername",
   288  							},
   289  						},
   290  						Scope:     []string{"PARAMETERS"},
   291  						Type:      "string",
   292  						Mandatory: false,
   293  						Aliases:   []config.Alias{},
   294  						Default:   os.Getenv("PIPER_username"),
   295  					},
   296  					{
   297  						Name: "password",
   298  						ResourceRef: []config.ResourceReference{
   299  							{
   300  								Name:  "nexusCredentialsId",
   301  								Param: "password",
   302  								Type:  "secret",
   303  							},
   304  
   305  							{
   306  								Name:  "commonPipelineEnvironment",
   307  								Param: "custom/repositoryPassword",
   308  							},
   309  						},
   310  						Scope:     []string{"PARAMETERS"},
   311  						Type:      "string",
   312  						Mandatory: false,
   313  						Aliases:   []config.Alias{},
   314  						Default:   os.Getenv("PIPER_password"),
   315  					},
   316  				},
   317  			},
   318  			Containers: []config.Container{
   319  				{Name: "mvn-npm", Image: "devxci/mbtci-java11-node14"},
   320  			},
   321  		},
   322  	}
   323  	return theMetaData
   324  }