utils

package
v2.37.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2023 License: Apache-2.0 Imports: 41 Imported by: 1

Documentation

Index

Constants

View Source
const (
	InsertValuePromptMsg = "Insert the value for "
	DummyDefaultAnswer   = "-"
)
View Source
const (
	PressTabMsg      = " (press Tab for options):"
	InvalidAnswerMsg = "Invalid answer. Please select value from the suggestions list."
	VariableUseMsg   = " You may use dynamic variable in the form of ${key}."
	EmptyValueMsg    = "The value cannot be empty. Please enter a valid value."
	OptionalKey      = "OptionalKey"
	SaveAndExit      = ":x"

	// Boolean answers
	True  = "true"
	False = "false"

	CommaSeparatedListMsg = "The value should be a comma separated list"
)
View Source
const BuildConfVersion = 1
View Source
const PathErrorSuffixMsg = " please enter a path, in which the new template file will be created"

Variables

View Source
var FreeStringQuestionInfo = QuestionInfo{
	Options:   nil,
	AllowVars: false,
	Writer:    WriteStringAnswer,
}

Common questions

View Source
var VarPattern = regexp.MustCompile(`^\$\{\w+}+$`)

Var can be inserted in the form of ${key}

Functions

func AskFromList

func AskFromList(msg, promptPrefix string, allowVars bool, options []prompt.Suggest, defaultValue string) string

Ask question with list of possible answers. If answer is empty and defaultValue isn't, return defaultValue. Otherwise, the answer must be chosen from the list, but can be a variable if allowVars set to true.

func AskFromListWithMismatchConfirmation

func AskFromListWithMismatchConfirmation(promptPrefix, misMatchMsg string, options []prompt.Suggest) string

Ask question with list of possible answers. If the provided answer does not appear in list, confirm the choice.

func AskString

func AskString(msg, promptPrefix string, allowEmpty bool, allowVars bool) string

Ask question with free string answer, allow an empty string as an answer

func AskStringWithDefault

func AskStringWithDefault(msg, promptPrefix, defaultValue string) string

Ask question with free string answer. If answer is empty and defaultValue isn't, return defaultValue. Otherwise, answer cannot be empty. Variable aren't checked and can be part of the answer.

func BackupFile added in v2.2.1

func BackupFile(filePath, backupPath string) (restore func() error, err error)

BackupFile creates a backup of the file in filePath. The backup will be found at backupPath. The returned restore function can be called to restore the file's state - the file in filePath will be replaced by the backup in backupPath. If there is no file at filePath, a backup file won't be created, and the restore function will delete the file at filePath.

func ConvertTemplateToMap

func ConvertTemplateToMap(tuc TemplateUserCommand) (map[string]interface{}, error)

func ConvertToSuggests

func ConvertToSuggests(options []string) []prompt.Suggest

func CreateArtifactoryClientDetails added in v2.27.0

func CreateArtifactoryClientDetails(serviceManager artifactory.ArtifactoryServicesManager) (*httputils.HttpClientDetails, error)

func CreateBuildConfig

func CreateBuildConfig(c *cli.Context, confType utils.ProjectType) (err error)

func CreateCSVFile added in v2.28.0

func CreateCSVFile(filePrefix string, items interface{}, timeStarted time.Time) (csvPath string, err error)

func CreateCollectChecksumsFunc added in v2.10.0

func CreateCollectChecksumsFunc(previousBuildDependencies map[string]*entities.Dependency, servicesManager artifactory.ArtifactoryServicesManager, missingDepsChan chan string) func(dependency *entities.Dependency) (bool, error)

func ExtractDockerOptionsFromArgs added in v2.10.0

func ExtractDockerOptionsFromArgs(args []string) (threads int, serverDetails *config.ServerDetails, detailedSummary, skipLogin bool, cleanArgs []string, buildConfig *utils.BuildConfiguration, err error)

Remove all the none docker CLI flags from args.

func ExtractNpmOptionsFromArgs

func ExtractNpmOptionsFromArgs(args []string) (detailedSummary, xrayScan bool, scanOutputFormat xrutils.OutputFormat, cleanArgs []string, buildConfig *utils.BuildConfiguration, err error)

Remove all the none npm CLI flags from args.

func ExtractYarnOptionsFromArgs added in v2.10.0

func ExtractYarnOptionsFromArgs(args []string) (threads int, detailedSummary, xrayScan bool, scanOutputFormat xrutils.OutputFormat, cleanArgs []string, buildConfig *utils.BuildConfiguration, err error)

func GetArtifactoryNpmRepoDetails

func GetArtifactoryNpmRepoDetails(repo string, authArtDetails *auth.ServiceDetails) (npmAuth, registry string, err error)

func GetBoolSuggests

func GetBoolSuggests() []prompt.Suggest

func GetCurationOutputFormat added in v2.33.0

func GetCurationOutputFormat(formatFlagVal string) (format xrutils.OutputFormat, err error)

func GetDependenciesFromLatestBuild

func GetDependenciesFromLatestBuild(servicesManager artifactory.ArtifactoryServicesManager, buildName string) (map[string]*entities.Dependency, error)

func GetSuggestsFromKeys

func GetSuggestsFromKeys(keys []string, suggestionMap map[string]prompt.Suggest) []prompt.Suggest

func GetTransferPluginVersion added in v2.18.1

func GetTransferPluginVersion(client *jfroghttpclient.JfrogHttpClient, url, pluginName string, serverType ServerType, rtDetails *httputils.HttpClientDetails) (string, error)

func GetXrayOutputFormat added in v2.4.1

func GetXrayOutputFormat(formatFlagVal string) (format xrutils.OutputFormat, err error)

func InterfaceToMap added in v2.29.8

func InterfaceToMap(jsonInterface interface{}) (map[string]interface{}, error)

Convert the input JSON interface to a map. jsonInterface - JSON interface, such as repository params

func OptionalKeyCallback

func OptionalKeyCallback(iq *InteractiveQuestionnaire, key string) (value string, err error)

After an optional value was chosen we'll ask for its value.

func PrintMissingDependencies

func PrintMissingDependencies(missingDependencies []string)

func ScanDeployableArtifacts

func ScanDeployableArtifacts(deployableArtifacts *Result, serverDetails *config.ServerDetails, threads int, format xrutils.OutputFormat) (*spec.SpecFiles, *spec.SpecFiles, error)

ScanDeployableArtifacts scans all files founds in the given parsed deployableArtifacts results. If the scan passes, the function returns two file-specs ready for upload. The first one contains all the binaries and the second all the "pom.xml"s. If one of the file's scan failed both of the return values will be nil.

func ValidateMapEntry

func ValidateMapEntry(key string, value interface{}, writersMap map[string]AnswerWriter) error

func ValidateTemplatePath

func ValidateTemplatePath(templatePath string) error

func WriteBoolAnswer

func WriteBoolAnswer(resultMap *map[string]interface{}, key, value string) error

func WriteIntAnswer

func WriteIntAnswer(resultMap *map[string]interface{}, key, value string) error

func WriteStringAnswer

func WriteStringAnswer(resultMap *map[string]interface{}, key, value string) error

Common writers

func WriteStringArrayAnswer

func WriteStringArrayAnswer(resultMap *map[string]interface{}, key, value string) error

Types

type AnswerWriter

type AnswerWriter func(resultMap *map[string]interface{}, key, value string) error

Each question can have the following properties:

  • Msg - will be printed in separate line
  • PromptPrefix - will be printed before the input cursor in the answer line
  • Options - In case the answer must be selected from a predefined list
  • AllowVars - a flag indicates whether a variable (in form of ${var}) is an acceptable answer despite the predefined list
  • Writer - how to write the answer to the final config map
  • MapKey - the key under which the answer will be written to the configMap
  • Callback - optional function can be executed after the answer was inserted. Can be used to implement some dependencies between questions.

type ConditionalUploadScanFuncType added in v2.9.0

type ConditionalUploadScanFuncType func(serverDetails *config.ServerDetails, fileSpec *spec.SpecFiles, threads int, scanOutputFormat xrutils.OutputFormat) error
var ConditionalUploadScanFunc ConditionalUploadScanFuncType = conditionalUploadDefaultScanFunc

Function to run as a condition to upload. If not overridden, the default scan function is used.

type ConfigFile

type ConfigFile struct {
	Interactive bool             `yaml:"-"`
	Version     int              `yaml:"version,omitempty"`
	ConfigType  string           `yaml:"type,omitempty"`
	Resolver    utils.Repository `yaml:"resolver,omitempty"`
	Deployer    utils.Repository `yaml:"deployer,omitempty"`
	UsePlugin   bool             `yaml:"usePlugin,omitempty"`
	UseWrapper  bool             `yaml:"useWrapper,omitempty"`
}

func NewConfigFile

func NewConfigFile(confType utils.ProjectType, c *cli.Context) *ConfigFile

func (*ConfigFile) VerifyConfigFile

func (configFile *ConfigFile) VerifyConfigFile(configFilePath string) error

Verify config file doesn't exist or prompt to override it

type InteractiveQuestionnaire

type InteractiveQuestionnaire struct {
	QuestionsMap           map[string]QuestionInfo
	MandatoryQuestionsKeys []string
	OptionalKeysSuggests   []prompt.Suggest
	AnswersMap             map[string]interface{}
}

The interactive questionnaire works as follows:

We have to provide a map of QuestionInfo which include all possible questions may be asked.
1. Mandatory Questions:
	* We will ask all the questions in MandatoryQuestionsKeys list one after the other.
2. Optional questions:
	* We have to provide a slice of prompt.Suggest, in which each suggest.Text is a key of a question in the map.
	* After a suggest was chosen from the list, the corresponding question from the map will be asked.
	* Each answer is written to the configMap using its writer, under the MapKey specified in the questionInfo.
	* We will execute the previous step until the SaveAndExit string was inserted.

func (*InteractiveQuestionnaire) AskQuestion

func (iq *InteractiveQuestionnaire) AskQuestion(question QuestionInfo) (value string, err error)

Ask question steps:

  1. Ask for string/from list
  2. Write the answer to answersMap (if writer provided)
  3. Run callback (if provided)

func (*InteractiveQuestionnaire) Perform

func (iq *InteractiveQuestionnaire) Perform() error

The main function to perform the questionnaire

type PreCheck added in v2.25.0

type PreCheck interface {
	// Name - Describes the check
	Name() string
	// Execute the check, return true if passed
	ExecuteCheck(args RunArguments) (bool, error)
}

PreCheck Is interface for a check on an Artifactory server

func NewCheck added in v2.25.0

func NewCheck(name string, check func(args RunArguments) (bool, error)) PreCheck

NewCheck - Creates a check base on a given function and name

type PreCheckRunner added in v2.25.0

type PreCheckRunner struct {
	// contains filtered or unexported fields
}

PreCheckRunner - Manages and runs the pre-checks

func NewPreChecksRunner added in v2.25.0

func NewPreChecksRunner() *PreCheckRunner

Creates a new empty runner

func (*PreCheckRunner) AddCheck added in v2.25.0

func (pcr *PreCheckRunner) AddCheck(check PreCheck)

Add a check to the runner

func (*PreCheckRunner) Run added in v2.25.0

func (pcr *PreCheckRunner) Run(context context.Context, serverDetails *config.ServerDetails) (err error)

Run all the checks and display the process

type QuestionInfo

type QuestionInfo struct {
	Msg          string
	PromptPrefix string
	Options      []prompt.Suggest
	AllowVars    bool
	Writer       AnswerWriter
	MapKey       string
	Callback     questionCallback
}

type RemoteRepositoryCheck added in v2.27.0

type RemoteRepositoryCheck struct {
	// contains filtered or unexported fields
}

Run remote repository URLs accessibility test before transferring configuration from one Artifactory to another

func NewRemoteRepositoryCheck added in v2.27.0

func NewRemoteRepositoryCheck(targetServicesManager *artifactory.ArtifactoryServicesManager, remoteRepositories []interface{}) *RemoteRepositoryCheck

func (*RemoteRepositoryCheck) ExecuteCheck added in v2.27.0

func (rrc *RemoteRepositoryCheck) ExecuteCheck(args RunArguments) (passed bool, err error)

func (*RemoteRepositoryCheck) Name added in v2.27.0

func (rrc *RemoteRepositoryCheck) Name() string

type RemoteUrlCheckStatus added in v2.27.0

type RemoteUrlCheckStatus string

type Result

type Result struct {
	// contains filtered or unexported fields
}

func UnmarshalDeployableArtifacts

func UnmarshalDeployableArtifacts(deployableArtifactsFilePath, projectConfigPath string, lateDeploy bool) (*Result, error)

UnmarshalDeployableArtifacts reads and parses the deployed artifacts details from the provided file. The details were written by Build-info project while deploying artifacts to maven and gradle repositories. deployableArtifactsFilePath - path to deployableArtifacts file written by Build-info project. projectConfigPath - path to gradle/maven config yaml path. lateDeploy - boolean indicates if the artifacts was expected to be deployed.

func (*Result) FailCount

func (r *Result) FailCount() int

func (*Result) Reader

func (r *Result) Reader() *content.ContentReader

func (*Result) SetFailCount

func (r *Result) SetFailCount(failCount int)

func (*Result) SetReader

func (r *Result) SetReader(reader *content.ContentReader)

func (*Result) SetSuccessCount

func (r *Result) SetSuccessCount(successCount int)

func (*Result) SuccessCount

func (r *Result) SuccessCount() int

type RunArguments added in v2.25.0

type RunArguments struct {
	Context       context.Context
	ServerDetails *config.ServerDetails
	ProgressMng   *progressbar.ProgressBarMng
}

RunArguments - The arguments of the run that is passed to the checks

type RunStatus added in v2.25.0

type RunStatus struct {
	// contains filtered or unexported fields
}

RunStatus - The status of the preformed checks in a run

type RunnerProgressBar added in v2.25.0

type RunnerProgressBar struct {
	// contains filtered or unexported fields
}

Manage all the displayed progress of the run

type ServerType added in v2.19.1

type ServerType string
const (
	Source                ServerType = "source"
	Target                ServerType = "target"
	PluginsExecuteRestApi            = "api/plugins/execute/"
)

type TemplateUserCommand

type TemplateUserCommand interface {
	// Returns the file path.
	TemplatePath() string
	// Returns vars to replace in the template content.
	Vars() string
}

type TransferConfigBase added in v2.29.8

type TransferConfigBase struct {
	SourceServerDetails      *config.ServerDetails
	TargetServerDetails      *config.ServerDetails
	SourceArtifactoryManager artifactory.ArtifactoryServicesManager
	TargetArtifactoryManager artifactory.ArtifactoryServicesManager
	IncludeReposPatterns     []string
	ExcludeReposPatterns     []string
	FederatedMembersRemoved  bool
}

func NewTransferConfigBase added in v2.29.8

func NewTransferConfigBase(sourceServer, targetServer *config.ServerDetails) *TransferConfigBase

func (*TransferConfigBase) CreateServiceManagers added in v2.29.8

func (tcb *TransferConfigBase) CreateServiceManagers(dryRun bool) (err error)

func (*TransferConfigBase) DeactivateKeyEncryption added in v2.29.8

func (tcb *TransferConfigBase) DeactivateKeyEncryption() (reactivateKeyEncryption func() error, err error)

Deactivate key encryption in Artifactory, to allow retrieving raw text values in the artifactory-config.xml or in a remote repository.

func (*TransferConfigBase) GetAllRemoteRepositories added in v2.29.8

func (tcb *TransferConfigBase) GetAllRemoteRepositories(remoteRepositoryNames []string) ([]interface{}, error)

Get all remote repositories. This method must run after disabling Artifactory key encryption. remoteRepositoryNames - Remote repository names to transfer

func (*TransferConfigBase) GetRepoFilter added in v2.29.8

func (tcb *TransferConfigBase) GetRepoFilter() *utils.IncludeExcludeFilter

func (*TransferConfigBase) GetSelectedRepositories added in v2.29.8

func (tcb *TransferConfigBase) GetSelectedRepositories() (map[utils.RepoType][]string, error)

Create a map between the repository types to the list of repositories to transfer.

func (*TransferConfigBase) IsDefaultCredentials added in v2.29.8

func (tcb *TransferConfigBase) IsDefaultCredentials() (bool, error)

Check if there is a configured user using default credentials 'admin:password' by pinging Artifactory.

func (*TransferConfigBase) LogIfFederatedMemberRemoved added in v2.29.8

func (tcb *TransferConfigBase) LogIfFederatedMemberRemoved()

During the transfer-config commands we remove federated members, if existed. This method log an info that the federated members should be reconfigured in the target server.

func (*TransferConfigBase) LogTitle added in v2.29.8

func (tcb *TransferConfigBase) LogTitle(title string)

func (*TransferConfigBase) SetExcludeReposPatterns added in v2.29.8

func (tcb *TransferConfigBase) SetExcludeReposPatterns(excludeReposPatterns []string) *TransferConfigBase

func (*TransferConfigBase) SetIncludeReposPatterns added in v2.29.8

func (tcb *TransferConfigBase) SetIncludeReposPatterns(includeReposPatterns []string) *TransferConfigBase

func (*TransferConfigBase) TransferRepositoriesToTarget added in v2.29.8

func (tcb *TransferConfigBase) TransferRepositoriesToTarget(reposToTransfer map[utils.RepoType][]string, remoteRepositories []interface{}) (err error)

Transfer all repositories to the target Artifactory server reposToTransfer - Map between a repository type to the list of repository names remoteRepositories - Remote repositories params, we get the remote repository params in an earlier stage after decryption

func (*TransferConfigBase) ValidateDifferentServers added in v2.34.0

func (tcb *TransferConfigBase) ValidateDifferentServers() error

Make sure source and target Artifactory URLs are different.

type VersionResponse added in v2.18.1

type VersionResponse struct {
	Version string `json:"version,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL