Esempio n. 1
0
func prepareLicenseFile(filepath string, overrideFile bool) (err error) {
	if filepath == "" {
		return
	}
	var dir bool
	dir, err = ioutils.IsDir(filepath)
	if err != nil {
		return
	}
	if dir {
		err = cliutils.CheckError(errors.New(filepath + " is a directory."))
		if err != nil {
			return
		}
	}
	var exists bool
	exists, err = ioutils.IsFileExists(filepath)
	if err != nil {
		return
	}
	if !overrideFile && exists {
		err = cliutils.CheckError(errors.New("File already exist, in case you wish to override the file use --override flag"))
		if err != nil {
			return
		}
	}
	_, directory := ioutils.GetFileAndDirFromPath(filepath)
	isPathExists := ioutils.IsPathExists(directory)
	if !isPathExists {
		os.MkdirAll(directory, 0700)
	}
	err = ioutil.WriteFile(filepath, nil, 0777)
	err = cliutils.CheckError(err)
	return
}
Esempio n. 2
0
func AddInstance(instanceName string, flags *AddInstanceFlags) error {
	data := AddInstanceRequestContent{
		Name:        instanceName,
		Url:         flags.ArtifactoryInstanceDetails.Url,
		User:        flags.ArtifactoryInstanceDetails.User,
		Password:    flags.ArtifactoryInstanceDetails.Password,
		Description: flags.Description,
		Location:    flags.Location}
	requestContent, err := json.Marshal(data)
	if err != nil {
		return cliutils.CheckError(errors.New("Failed to execute request. " + cliutils.GetDocumentationMessage()))
	}
	missionControlUrl := flags.MissionControlDetails.Url + "api/v1/instances"
	httpClientDetails := utils.GetMissionControlHttpClientDetails(flags.MissionControlDetails)
	resp, body, err := ioutils.SendPost(missionControlUrl, requestContent, httpClientDetails)
	if err != nil {
		return err
	}
	if resp.StatusCode == 201 || resp.StatusCode == 204 {
		fmt.Println("Mission Control response: " + resp.Status)
	} else {
		return cliutils.CheckError(errors.New(resp.Status + ". " + utils.ReadMissionControlHttpMessage(body)))
	}
	return nil
}
Esempio n. 3
0
func getFilesList(flags *OfflineUpdatesFlags) ([]string, []string, int64, error) {
	log.Info("Getting updates...")
	headers := make(map[string]string)
	headers["X-Xray-License"] = flags.License
	httpClientDetails := ioutils.HttpClientDetails{
		Headers: headers,
	}
	resp, body, _, err := ioutils.SendGet(updatesUrl, false, httpClientDetails)
	if err != nil {
		cliutils.CheckError(err)
		return nil, nil, 0, err
	}
	if resp.StatusCode != 200 {
		err := errors.New("Response: " + resp.Status)
		cliutils.CheckError(err)
		return nil, nil, 0, err
	}
	var urls FilesList
	json.Unmarshal(body, &urls)
	var vulnerabilities, components []string
	for _, v := range urls.Urls {
		if strings.Contains(v, VULNERABILITY) {
			vulnerabilities = append(vulnerabilities, v)
		} else if strings.Contains(v, COMPONENT) {
			components = append(components, v)
		}
	}
	return vulnerabilities, components, urls.Last_update, nil
}
Esempio n. 4
0
func SaveBuildGeneralDetails(buildName, buildNumber string) error {
	path, err := GetBuildDir(buildName, buildNumber)
	if err != nil {
		return err
	}
	path += BUILD_INFO_DETAILS
	var exists bool
	exists, err = ioutils.IsFileExists(path)
	if err != nil {
		return err
	}
	if exists {
		return nil
	}
	meta := BuildGeneralDetails{
		Timestamp: time.Now(),
	}
	b, err := json.Marshal(&meta)
	err = cliutils.CheckError(err)
	var content bytes.Buffer
	err = json.Indent(&content, b, "", "  ")
	err = cliutils.CheckError(err)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(path, []byte(content.String()), 0600)
	return err
}
Esempio n. 5
0
func GetFileDetails(filePath string) (*FileDetails, error) {
	var err error
	details := new(FileDetails)
	details.Md5, err = calcMd5(filePath)
	if err != nil {
		return nil, err
	}
	details.Sha1, err = calcSha1(filePath)
	if err != nil {
		return nil, err
	}

	file, err := os.Open(filePath)
	err = cliutils.CheckError(err)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	fileInfo, err := file.Stat()
	err = cliutils.CheckError(err)
	if err != nil {
		return nil, err
	}
	details.Size = fileInfo.Size()
	return details, nil
}
Esempio n. 6
0
func DownloadFileConcurrently(flags ConcurrentDownloadFlags, logMsgPrefix string, httpClientsDetails HttpClientDetails) error {
	var wg sync.WaitGroup
	chunkSize := flags.FileSize / int64(flags.SplitCount)
	mod := flags.FileSize % int64(flags.SplitCount)
	var err error
	for i := 0; i < flags.SplitCount; i++ {
		if err != nil {
			break
		}
		wg.Add(1)
		start := chunkSize * int64(i)
		end := chunkSize * (int64(i) + 1)
		if i == flags.SplitCount-1 {
			end += mod
		}
		requestClientDetails := httpClientsDetails.Clone()
		go func(start, end int64, i int) {
			e := downloadFileRange(flags, start, end, i, logMsgPrefix, *requestClientDetails)
			if e != nil {
				err = e
			}
			wg.Done()
		}(start, end, i)
	}
	wg.Wait()

	if err != nil {
		return err
	}

	if !flags.Flat && flags.LocalPath != "" {
		os.MkdirAll(flags.LocalPath, 0777)
		flags.FileName = flags.LocalPath + "/" + flags.FileName
	}

	if IsPathExists(flags.FileName) {
		err := os.Remove(flags.FileName)
		err = cliutils.CheckError(err)
		if err != nil {
			return err
		}
	}

	destFile, err := os.Create(flags.FileName)
	err = cliutils.CheckError(err)
	if err != nil {
		return err
	}
	defer destFile.Close()
	for i := 0; i < flags.SplitCount; i++ {
		tempFilePath, err := GetTempDirPath()
		if err != nil {
			return err
		}
		tempFilePath += "/" + flags.FileName + "_" + strconv.Itoa(i)
		AppendFile(tempFilePath, destFile)
	}
	fmt.Println(logMsgPrefix + "Done downloading.")
	return nil
}
Esempio n. 7
0
func DownloadVersion(versionDetails *utils.VersionDetails, targetPath string, flags *utils.DownloadFlags) (totalDownloded, totalFailed int, err error) {
	ioutils.CreateTempDirPath()
	defer ioutils.RemoveTempDir()

	if flags.BintrayDetails.User == "" {
		flags.BintrayDetails.User = versionDetails.Subject
	}
	path := BuildDownloadVersionUrl(versionDetails, flags.BintrayDetails, flags.IncludeUnpublished)
	httpClientsDetails := utils.GetBintrayHttpClientDetails(flags.BintrayDetails)
	resp, body, _, _ := ioutils.SendGet(path, true, httpClientsDetails)
	if resp.StatusCode != 200 {
		err = cliutils.CheckError(errors.New(resp.Status + ". " + utils.ReadBintrayMessage(body)))
		return
	}
	var results []VersionFilesResult
	err = json.Unmarshal(body, &results)
	if cliutils.CheckError(err) != nil {
		return
	}

	totalDownloded, err = downloadFiles(results, versionDetails, targetPath, flags)
	log.Info("Downloaded", strconv.Itoa(totalDownloded), "artifacts.")
	totalFailed = len(results) - totalDownloded
	return
}
Esempio n. 8
0
func getOfflineUpdatesFlag(c *cli.Context) (flags *commands.OfflineUpdatesFlags, err error) {
	flags = new(commands.OfflineUpdatesFlags)
	flags.License = c.String("license-id")
	if len(flags.License) < 1 {
		cliutils.Exit(cliutils.ExitCodeError, "The --license-id option is mandatory")
	}
	from := c.String("from")
	to := c.String("to")
	if len(to) > 0 && len(from) < 1 {
		cliutils.Exit(cliutils.ExitCodeError, "The --from option is mandatory, when the --to option is sent.")
	}
	if len(from) > 0 && len(to) < 1 {
		cliutils.Exit(cliutils.ExitCodeError, "The --to option is mandatory, when the --from option is sent.")
	}
	if len(from) > 0 && len(to) > 0 {
		flags.From, err = dateToMilliseconds(from)
		cliutils.CheckError(err)
		if err != nil {
			return
		}
		flags.To, err = dateToMilliseconds(to)
		cliutils.CheckError(err)
	}
	return
}
Esempio n. 9
0
func Config(details, defaultDetails *config.MissionControlDetails, interactive bool) (conf *config.MissionControlDetails, err error) {
	conf = details
	if conf == nil {
		conf = new(config.MissionControlDetails)
	}
	if interactive {
		if defaultDetails == nil {
			defaultDetails, err = config.ReadMissionControlConf()
			if err != nil {
				return
			}
		}
		if conf.Url == "" {
			ioutils.ScanFromConsole("Mission Control URL", &conf.Url, defaultDetails.Url)
			var u *url.URL
			u, err = url.Parse(conf.Url)
			err = cliutils.CheckError(err)
			if err != nil {
				return
			}
			if u.Scheme != "http" && u.Scheme != "https" {
				err = cliutils.CheckError(errors.New("URL scheme is not valid " + u.Scheme))
				if err != nil {
					return
				}
			}
		}
		ioutils.ReadCredentialsFromConsole(conf, defaultDetails)
	}
	conf.Url = cliutils.AddTrailingSlashIfNeeded(conf.Url)
	config.SaveMissionControlConf(conf)
	return
}
Esempio n. 10
0
func saveConfig(config *Config) error {
	b, err := json.Marshal(&config)
	err = cliutils.CheckError(err)
	if err != nil {
		return err
	}
	var content bytes.Buffer
	err = json.Indent(&content, b, "", "  ")
	err = cliutils.CheckError(err)
	if err != nil {
		return err
	}
	path, err := getConFilePath()
	if err != nil {
		return err
	}
	var exists bool
	exists, err = ioutils.IsFileExists(path)
	if err != nil {
		return err
	}
	if exists {
		err := os.Remove(path)
		err = cliutils.CheckError(err)
		if err != nil {
			return err
		}
	}
	path, err = getConFilePath()
	if err != nil {
		return err
	}
	ioutil.WriteFile(path, []byte(content.String()), 0600)
	return nil
}
Esempio n. 11
0
func parseUrl(url string) (protocol, host string, port int, err error) {
	pattern1 := "^(.+)://(.+):([0-9].+)/$"
	pattern2 := "^(.+)://(.+)$"

	var r *regexp.Regexp
	r, err = regexp.Compile(pattern1)
	err = cliutils.CheckError(err)
	if err != nil {
		return
	}
	groups := r.FindStringSubmatch(url)
	if len(groups) == 4 {
		protocol = groups[1]
		host = groups[2]
		port, err = strconv.Atoi(groups[3])
		if err != nil {
			err = cliutils.CheckError(errors.New("URL: " + url + " is invalid. Expecting ssh://<host>:<port> or http(s)://..."))
		}
		return
	}

	r, err = regexp.Compile(pattern2)
	err = cliutils.CheckError(err)
	if err != nil {
		return
	}
	groups = r.FindStringSubmatch(url)
	if len(groups) == 3 {
		protocol = groups[1]
		host = groups[2]
		port = 80
	}
	return
}
Esempio n. 12
0
func prepareBuildInfoData(artifactsDataWrapper utils.BuildInfo, includeFilter, excludeFilter filterFunc) ([]utils.ArtifactBuildInfo, []utils.DependenciesBuildInfo, utils.BuildEnv, error) {
	var artifacts []utils.ArtifactBuildInfo
	var dependencies []utils.DependenciesBuildInfo
	var env utils.BuildEnv
	env = make(map[string]string)
	for _, buildInfoData := range artifactsDataWrapper {
		switch {
		case buildInfoData.Artifacts != nil:
			for _, v := range buildInfoData.Artifacts {
				artifacts = append(artifacts, v)
			}
		case buildInfoData.Dependencies != nil:
			for _, v := range buildInfoData.Dependencies {
				dependencies = append(dependencies, v)
			}
		case buildInfoData.Env != nil:
			envAfterIncludeFilter, e := includeFilter(buildInfoData.Env)
			if cliutils.CheckError(e) != nil {
				return artifacts, dependencies, env, e
			}
			envAfterExcludeFilter, e := excludeFilter(envAfterIncludeFilter)
			if cliutils.CheckError(e) != nil {
				return artifacts, dependencies, env, e
			}
			for k, v := range envAfterExcludeFilter {
				env[k] = v
			}
		}
	}
	return artifacts, dependencies, env, nil
}
Esempio n. 13
0
func BuildPublish(buildName, buildNumber string, flags *utils.BuildInfoFlags) error {
	err := utils.PreCommandSetup(flags)
	if err != nil {
		return err
	}

	buildData, err := utils.ReadBuildInfoFiles(buildName, buildNumber)
	if err != nil {
		return err
	}

	if len(buildData) == 0 {
		return cliutils.CheckError(fmt.Errorf("Can't find any files related to build name: %q, number: %q", buildName, buildNumber))
	}
	sort.Sort(buildData)
	buildInfo := createNewBuildInfo()
	buildInfo.Name = buildName
	buildInfo.Number = buildNumber
	buildGeneralDetails, err := utils.ReadBuildInfoGeneralDetails(buildName, buildNumber)
	if err != nil {
		return err
	}
	buildInfo.Started = buildGeneralDetails.Timestamp.Format("2006-01-02T15:04:05.000-0700")
	artifactsSet, dependenciesSet, env, err := prepareBuildInfoData(buildData, createIncludeFilter(flags), createExcludeFilter(flags))
	if err != nil {
		return err
	}
	if len(env) != 0 {
		buildInfo.Propertires = env
	}
	module := createModule(buildName, artifactsSet, dependenciesSet)
	buildInfo.Modules = append(buildInfo.Modules, module)
	marshaledBuildInfo, err := json.Marshal(buildInfo)
	if cliutils.CheckError(err) != nil {
		return err
	}
	if flags.IsDryRun() {
		fmt.Println(cliutils.IndentJson(marshaledBuildInfo))
		return nil
	}
	httpClientsDetails := utils.GetArtifactoryHttpClientDetails(flags.ArtDetails)
	utils.SetContentType("application/vnd.org.jfrog.artifactory+json", &httpClientsDetails.Headers)
	log.Info("Deploying build info...")
	resp, body, err := utils.PublishBuildInfo(flags.ArtDetails.Url, marshaledBuildInfo, httpClientsDetails)
	if err != nil {
		return err
	}
	if resp.StatusCode != 204 {
		return cliutils.CheckError(errors.New("Artifactory response: " + resp.Status + "\n" + cliutils.IndentJson(body)))
	}

	log.Debug("Artifactory response:", resp.Status)
	log.Info("Build info successfully deployed. Browse it in Artifactory under " + flags.ArtDetails.Url + "webapp/builds/" + buildName + "/" + buildNumber)
	if err = utils.RemoveBuildDir(buildName, buildNumber); err != nil {
		return err
	}
	return nil
}
Esempio n. 14
0
func zipFolderFiles(source, target string) (err error) {
	zipfile, err := os.Create(target)
	if err != nil {
		cliutils.CheckError(err)
		return
	}
	defer func() {
		if cerr := zipfile.Close(); cerr != nil && err == nil {
			err = cerr
		}
	}()

	archive := zip.NewWriter(zipfile)
	defer func() {
		if cerr := archive.Close(); cerr != nil && err == nil {
			err = cerr
		}
	}()

	filepath.Walk(source, func(path string, info os.FileInfo, err error) (currentErr error) {
		if info.IsDir() {
			return
		}

		if err != nil {
			currentErr = err
			return
		}

		header, currentErr := zip.FileInfoHeader(info)
		if currentErr != nil {
			cliutils.CheckError(currentErr)
			return
		}

		header.Method = zip.Deflate
		writer, currentErr := archive.CreateHeader(header)
		if currentErr != nil {
			cliutils.CheckError(currentErr)
			return
		}

		file, currentErr := os.Open(path)
		if currentErr != nil {
			cliutils.CheckError(currentErr)
			return
		}
		defer func() {
			if cerr := file.Close(); cerr != nil && currentErr == nil {
				currentErr = cerr
			}
		}()
		_, currentErr = io.Copy(writer, file)
		return
	})
	return
}
Esempio n. 15
0
func BuildDistribute(buildName, buildNumber, targetRepo string, flags *BuildDistributionFlags) error {
	err := utils.PreCommandSetup(flags)
	if err != nil {
		return err
	}

	dryRun := ""
	if flags.DryRun == true {
		dryRun = "[Dry run] "
	}
	message := "Destributing build..."
	log.Info(dryRun + message)

	distributeUrl := flags.ArtDetails.Url
	restApi := path.Join("api/build/distribute/", buildName, buildNumber)
	requestFullUrl, err := utils.BuildArtifactoryUrl(distributeUrl, restApi, make(map[string]string))
	if err != nil {
		return err
	}

	data := BuildDistributionConfig{
		SourceRepos:           strings.Split(flags.SourceRepos, ","),
		TargetRepo:            targetRepo,
		Publish:               flags.Publish,
		OverrideExistingFiles: flags.OverrideExistingFiles,
		GpgPassphrase:         flags.GpgPassphrase,
		Async:                 flags.Async,
		DryRun:                flags.DryRun}
	requestContent, err := json.Marshal(data)
	if err != nil {
		return cliutils.CheckError(errors.New("Failed to execute request. " + cliutils.GetDocumentationMessage()))
	}

	httpClientsDetails := utils.GetArtifactoryHttpClientDetails(flags.ArtDetails)
	utils.SetContentType("application/json", &httpClientsDetails.Headers)

	resp, body, err := ioutils.SendPost(requestFullUrl, requestContent, httpClientsDetails)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return cliutils.CheckError(errors.New("Artifactory response: " + resp.Status + "\n" + cliutils.IndentJson(body)))
	}

	log.Debug("Artifactory response:", resp.Status)
	if flags.Async && !flags.DryRun {
		log.Info("Asynchronously distributed build", buildName, "#"+buildNumber, "to:", targetRepo, "repository, logs are avalable in Artifactory.")
		return nil
	}

	log.Info(dryRun+"Distributed build", buildName, "#"+buildNumber, "to:", targetRepo, "repository.")
	return nil
}
Esempio n. 16
0
func validateDates(from, to int64) (err error) {
	if from < 0 || to < 0 {
		err = errors.New("Invalid dates")
		cliutils.CheckError(err)
		return
	}
	if from > to {
		err = errors.New("Invalid dates range.")
		cliutils.CheckError(err)
		return
	}
	return
}
Esempio n. 17
0
func CreateTempDirPath() error {
	if tempDirPath != "" {
		err := cliutils.CheckError(errors.New("'tempDirPath' has already been initialized."))
		if err != nil {
			return err
		}
	}
	path, err := ioutil.TempDir("", "jfrog.cli.")
	err = cliutils.CheckError(err)
	if err != nil {
		return err
	}
	tempDirPath = path
	return nil
}
Esempio n. 18
0
func Config(details, defaultDetails *config.BintrayDetails, interactive bool) (*config.BintrayDetails, error) {
	if details == nil {
		details = new(config.BintrayDetails)
	}
	if interactive {
		if defaultDetails == nil {
			var err error
			defaultDetails, err = config.ReadBintrayConf()
			if err != nil {
				return nil, err
			}
		}
		if details.User == "" {
			ioutils.ScanFromConsole("User", &details.User, defaultDetails.User)
		}
		if details.Key == "" {
			print("Key: ")
			byteKey, err := terminal.ReadPassword(int(syscall.Stdin))
			err = cliutils.CheckError(err)
			if err != nil {
				return nil, err
			}
			details.Key = string(byteKey)
			if details.Key == "" {
				details.Key = defaultDetails.Key
			}
		}
		if details.DefPackageLicenses == "" {
			ioutils.ScanFromConsole("\nDefault package licenses",
				&details.DefPackageLicenses, defaultDetails.DefPackageLicenses)
		}
	}
	config.SaveBintrayConf(details)
	return details, nil
}
Esempio n. 19
0
func DeleteFiles(resultItems []utils.AqlSearchResultItem, flags *DeleteFlags) error {
	for _, v := range resultItems {
		fileUrl, err := utils.BuildArtifactoryUrl(flags.ArtDetails.Url, v.GetFullUrl(), make(map[string]string))
		if err != nil {
			return err
		}
		if flags.DryRun {
			log.Info("[Dry run] Deleting:", v.GetFullUrl())
			continue
		}

		log.Info("Deleting:", v.GetFullUrl())
		httpClientsDetails := utils.GetArtifactoryHttpClientDetails(flags.ArtDetails)
		resp, body, err := ioutils.SendDelete(fileUrl, nil, httpClientsDetails)
		if err != nil {
			return err
		}
		if resp.StatusCode != 204 {
			return cliutils.CheckError(errors.New("Artifactory response: " + resp.Status + "\n" + cliutils.IndentJson(body)))
		}

		log.Debug("Artifactory response:", resp.Status)
	}
	return nil
}
Esempio n. 20
0
func GpgSignFile(pathDetails *utils.PathDetails, passphrase string, bintrayDetails *config.BintrayDetails) error {
	if bintrayDetails.User == "" {
		bintrayDetails.User = pathDetails.Subject
	}
	url := bintrayDetails.ApiUrl + "gpg/" + pathDetails.Subject + "/" +
		pathDetails.Repo + "/" + pathDetails.Path

	var data string
	if passphrase != "" {
		data = "{ \"passphrase\": \"" + passphrase + "\" }"
	}

	log.Info("GPG signing file...")
	httpClientsDetails := utils.GetBintrayHttpClientDetails(bintrayDetails)
	resp, body, err := ioutils.SendPost(url, []byte(data), httpClientsDetails)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return cliutils.CheckError(errors.New("Bintray response: " + resp.Status + "\n" + cliutils.IndentJson(body)))
	}

	log.Debug("Bintray response:", resp.Status)
	log.Info("GPG signed file", pathDetails.Path, ", details:")
	fmt.Println(cliutils.IndentJson(body))
	return nil
}
Esempio n. 21
0
func ShowVersion(versionDetails *utils.VersionDetails, bintrayDetails *config.BintrayDetails) error {
	if bintrayDetails.User == "" {
		bintrayDetails.User = versionDetails.Subject
	}
	version := versionDetails.Version
	if versionDetails.Version == "" {
		versionDetails.Version = "_latest"
		version = "latest"
	}

	url := bintrayDetails.ApiUrl + "packages/" + versionDetails.Subject + "/" +
		versionDetails.Repo + "/" + versionDetails.Package + "/versions/" + versionDetails.Version

	log.Info("Getting version details...")
	httpClientsDetails := utils.GetBintrayHttpClientDetails(bintrayDetails)
	resp, body, _, _ := ioutils.SendGet(url, true, httpClientsDetails)

	if resp.StatusCode != 200 {
		return cliutils.CheckError(errors.New("Bintray response: " + resp.Status + "\n" + cliutils.IndentJson(body)))
	}

	log.Debug("Bintray response:", resp.Status)
	log.Info("Version", version, "details:")
	fmt.Println(cliutils.IndentJson(body))
	return nil
}
Esempio n. 22
0
func checkSingleAuthMethod(details *config.ArtifactoryDetails) (err error) {
	boolArr := []bool{details.User != "" && details.Password != "", details.ApiKey != "", details.SshKeyPath != ""}
	if cliutils.SumTrueValues(boolArr) > 1 {
		err = cliutils.CheckError(errors.New("Only one authentication method is allowd: Username/Password, API key or RSA tokens."))
	}
	return
}
Esempio n. 23
0
func getPackageFiles(packageName string) []tests.PackageSearchResultItem {
	apiUrl := bintrayConfig.ApiUrl + path.Join("packages", bintrayConfig.User, tests.BintrayRepo1, packageName, "files?include_unpublished=1")
	clientDetails := ioutils.HttpClientDetails{
		User:     bintrayConfig.User,
		Password: bintrayConfig.Key,
		Headers:  map[string]string{"Content-Type": "application/json"}}

	resp, body, _, err := ioutils.SendGet(apiUrl, true, clientDetails)
	if cliutils.CheckError(err) != nil {
		os.Exit(1)
	}
	if resp.StatusCode != 200 {
		log.Error(resp.Status)
		log.Error(string(body))
		os.Exit(1)
	}

	var result []tests.PackageSearchResultItem
	err = json.Unmarshal(body, &result)
	if err != nil {
		log.Error(err)
		os.Exit(1)
	}

	return result
}
Esempio n. 24
0
func MoveFilesWrapper(moveSpec *SpecFiles, flags *MoveFlags, moveType MoveType) (err error) {
	err = PreCommandSetup(flags)
	if err != nil {
		return
	}

	var successCount int
	var failedCount int

	for i := 0; i < len(moveSpec.Files); i++ {
		var successPartial, failedPartial int
		switch moveSpec.Get(i).GetSpecType() {
		case WILDCARD:
			successPartial, failedPartial, err = moveWildcard(moveSpec.Get(i), flags, moveType)
		case SIMPLE:
			successPartial, failedPartial, err = moveSimple(moveSpec.Get(i), flags, moveType)
		case AQL:
			successPartial, failedPartial, err = moveAql(moveSpec.Get(i), flags, moveType)
		}
		successCount += successPartial
		failedCount += failedPartial
		if err != nil {
			return
		}
	}

	log.Info(moveMsgs[moveType].MovedMsg, strconv.Itoa(successCount), "artifacts.")
	if failedCount > 0 {
		err = cliutils.CheckError(errors.New("Failed " + moveMsgs[moveType].MovingMsg + " " + strconv.Itoa(failedCount) + " artifacts."))
	}

	return
}
Esempio n. 25
0
func CreateVersionDetails(versionStr string) (*VersionDetails, error) {
	parts := strings.Split(versionStr, "/")
	size := len(parts)
	if size < 1 || size > 4 {
		err := cliutils.CheckError(errors.New("Unexpected format for argument: " + versionStr))
		if err != nil {
			return nil, err
		}
	}
	var subject, repo, pkg, version string
	if size >= 2 {
		subject = parts[0]
		repo = parts[1]
	}
	if size >= 3 {
		pkg = parts[2]
	}
	if size == 4 {
		version = parts[3]
	}
	return &VersionDetails{
		Subject: subject,
		Repo:    repo,
		Package: pkg,
		Version: version}, nil
}
Esempio n. 26
0
func Send(method string, url string, content []byte, allowRedirect bool,
	closeBody bool, httpClientsDetails HttpClientDetails) (resp *http.Response, respBody []byte, redirectUrl string, err error) {

	var req *http.Request
	if content != nil {
		req, err = http.NewRequest(method, url, bytes.NewBuffer(content))
	} else {
		req, err = http.NewRequest(method, url, nil)
	}
	err = cliutils.CheckError(err)
	if err != nil {
		return
	}
	req.Close = true

	setAuthentication(req, httpClientsDetails)
	addUserAgentHeader(req)

	if httpClientsDetails.Headers != nil {
		for name := range httpClientsDetails.Headers {
			req.Header.Set(name, httpClientsDetails.Headers[name])
		}
	}

	client := getHttpClient(httpClientsDetails.Transport)
	if !allowRedirect {
		client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
			redirectUrl = req.URL.String()
			return errors.New("redirect")
		}
	}

	resp, err = client.Do(req)
	if !allowRedirect && err != nil {
		return
	}

	err = cliutils.CheckError(err)
	if err != nil {
		return
	}
	if closeBody {
		defer resp.Body.Close()
		respBody, _ = ioutil.ReadAll(resp.Body)
	}
	return
}
Esempio n. 27
0
func saveLicense(filepath string, content []byte) (err error) {
	if filepath == "" {
		return
	}
	err = ioutil.WriteFile(filepath, content, 0777)
	err = cliutils.CheckError(err)
	return
}
Esempio n. 28
0
func calcSha1(filePath string) (string, error) {
	file, err := os.Open(filePath)
	cliutils.CheckError(err)
	if err != nil {
		return "", err
	}
	defer file.Close()

	var resSha1 []byte
	hashSha1 := sha1.New()
	_, err = io.Copy(hashSha1, file)
	err = cliutils.CheckError(err)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(hashSha1.Sum(resSha1)), nil
}
Esempio n. 29
0
func AttachLic(instanceName string, flags *AttachLicFlags) error {
	prepareLicenseFile(flags.LicensePath, flags.Override)
	postContent := utils.LicenseRequestContent{
		Name:   instanceName,
		NodeID: flags.NodeId,
		Deploy: flags.Deploy}
	requestContent, err := json.Marshal(postContent)
	if err != nil {
		return cliutils.CheckError(errors.New("Failed to marshal json. " + cliutils.GetDocumentationMessage()))
	}
	missionControlUrl := flags.MissionControlDetails.Url + "api/v1/buckets/" + flags.BucketId + "/licenses"
	httpClientDetails := utils.GetMissionControlHttpClientDetails(flags.MissionControlDetails)
	resp, body, err := ioutils.SendPost(missionControlUrl, requestContent, httpClientDetails)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		if flags.LicensePath != "" {
			os.Remove(flags.LicensePath)
		}
		return cliutils.CheckError(errors.New(resp.Status + ". " + utils.ReadMissionControlHttpMessage(body)))
	}
	fmt.Println("Mission Control response: " + resp.Status)
	if flags.LicensePath == "" {
		var m Message
		m, err = extractJsonValue(body)
		if err != nil {
			return err
		}
		requestContent, err = json.Marshal(m)
		err = cliutils.CheckError(err)
		if err != nil {
			return err
		}
		fmt.Println(string(requestContent))
	} else {
		var licenseKey []byte
		licenseKey, err = getLicenseFromJson(body)
		if err != nil {
			return err
		}
		err = saveLicense(flags.LicensePath, licenseKey)
	}
	return nil
}
Esempio n. 30
0
func GetBuildDir(buildName, buildNumber string) (string, error) {
	tempDir := os.TempDir()
	buildsDir := tempDir + "/jfrog/builds/" + buildName + "_" + buildNumber + "/"
	err := os.MkdirAll(buildsDir, 0777)
	if cliutils.CheckError(err) != nil {
		return "", err
	}
	return buildsDir, nil
}