Ejemplo n.º 1
0
// WriteStepSpecToFile ...
func WriteStepSpecToFile(templateCollection models.StepCollectionModel, route SteplibRoute) error {
	pth := GetStepSpecPath(route)

	if exist, err := pathutil.IsPathExists(pth); err != nil {
		log.Error("Failed to check path:", err)
		return err
	} else if !exist {
		dir, _ := path.Split(pth)
		err := os.MkdirAll(dir, 0777)
		if err != nil {
			return err
		}
	} else {
		err := os.Remove(pth)
		if err != nil {
			return err
		}
	}

	collection, err := generateStepLib(route, templateCollection)
	if err != nil {
		return err
	}

	bytes, err := json.MarshalIndent(collection, "", "\t")
	if err != nil {
		return err
	}
	return fileutil.WriteBytesToFile(pth, bytes)
}
Ejemplo n.º 2
0
// ExportFromKeychain ...
func ExportFromKeychain(itemRefsToExport []C.CFTypeRef, outputFilePath string, isAskForPassword bool) error {
	passphraseCString := C.CString("")
	defer C.free(unsafe.Pointer(passphraseCString))

	var exportedData C.CFDataRef
	var exportParams C.SecItemImportExportKeyParameters
	exportParams.keyUsage = nil
	exportParams.keyAttributes = nil
	exportParams.version = C.SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION
	if isAskForPassword {
		exportParams.flags = C.kSecKeySecurePassphrase
		exportParams.passphrase = nil
		exportParams.alertTitle = nil

		promptText := C.CString("Enter a password which will be used to protect the exported items")
		defer C.free(unsafe.Pointer(promptText))
		exportParams.alertPrompt = convertCStringToCFString(promptText)
	} else {
		exportParams.flags = 0
		exportParams.passphrase = (C.CFTypeRef)(convertCStringToCFString(passphraseCString))
		exportParams.alertTitle = nil
		exportParams.alertPrompt = nil
	}

	// create a C array from the input
	ptr := (*unsafe.Pointer)(&itemRefsToExport[0])
	cfArrayForExport := C.CFArrayCreate(
		C.kCFAllocatorDefault,
		ptr,
		C.CFIndex(len(itemRefsToExport)),
		&C.kCFTypeArrayCallBacks)

	// do the export!
	status := C.SecItemExport(C.CFTypeRef(cfArrayForExport),
		C.kSecFormatPKCS12,
		0, //C.kSecItemPemArmour, // Use kSecItemPemArmour to add PEM armour - the .p12 generated by Keychain Access.app does NOT have PEM armour
		&exportParams,
		&exportedData)

	if status != C.errSecSuccess {
		return fmt.Errorf("SecItemExport: error (OSStatus): %d", status)
	}
	// exportedData now contains your PKCS12 data
	//  make sure it'll be released properly!
	defer C.CFRelease(C.CFTypeRef(exportedData))

	dataBytes := convertCFDataRefToGoBytes(exportedData)
	if dataBytes == nil || len(dataBytes) < 1 {
		return errors.New("ExportFromKeychain: failed to convert export data - nil or empty")
	}

	if err := fileutil.WriteBytesToFile(outputFilePath, dataBytes); err != nil {
		return fmt.Errorf("ExportFromKeychain: failed to write into file: %s", err)
	}

	log.Debug("Export - success")

	return nil
}
Ejemplo n.º 3
0
func saveBitriseConfig(config ConfigModel) error {
	bytes, err := json.Marshal(config)
	if err != nil {
		return err
	}

	configPth := getBitriseConfigFilePath()
	return fileutil.WriteBytesToFile(configPth, bytes)
}
Ejemplo n.º 4
0
// WriteNewWorkflowModel ...
func WriteNewWorkflowModel(pth string, newWorkflow bitriseModels.BitriseDataModel) error {
	bytes, err := yaml.Marshal(newWorkflow)
	if err != nil {
		return err
	}
	if err := fileutil.WriteBytesToFile(pth, bytes); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 5
0
// SaveConfigToFile ...
func SaveConfigToFile(pth string, bitriseConf models.BitriseDataModel) error {
	contBytes, err := generateYAML(bitriseConf)
	if err != nil {
		return err
	}
	if err := fileutil.WriteBytesToFile(pth, contBytes); err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 6
0
// WriteShareSteplibToFile ...
func WriteShareSteplibToFile(share ShareModel) error {
	var bytes []byte
	bytes, err := json.MarshalIndent(share, "", "\t")
	if err != nil {
		log.Error("[STEPMAN] - Failed to parse json:", err)
		return err
	}

	return fileutil.WriteBytesToFile(getShareFilePath(), bytes)
}
// WritePlistToFile ...
func WritePlistToFile(options map[string]interface{}, pth string) error {
	plistBytes, err := plist.MarshalIndent(options, plist.XMLFormat, "\t")
	if err != nil {
		return fmt.Errorf("failed to marshal export options model, error: %s", err)
	}
	if err := fileutil.WriteBytesToFile(pth, plistBytes); err != nil {
		return fmt.Errorf("failed to write export options, error: %s", err)
	}

	return nil
}
Ejemplo n.º 8
0
func (routes SteplibRoutes) writeToFile() error {
	routeMap := map[string]string{}
	for _, route := range routes {
		routeMap[route.SteplibURI] = route.FolderAlias
	}
	bytes, err := json.MarshalIndent(routeMap, "", "\t")
	if err != nil {
		return err
	}
	return fileutil.WriteBytesToFile(getRoutingFilePath(), bytes)
}
Ejemplo n.º 9
0
// saveConfigs ...
//  only used for unit testing at the moment
func saveConfigs(configModel ConfigsModel) error {
	if err := ensureEnvmanConfigDirExists(); err != nil {
		return err
	}

	bytes, err := json.Marshal(configModel)
	if err != nil {
		return err
	}
	configsPth := getEnvmanConfigsFilePath()
	return fileutil.WriteBytesToFile(configsPth, bytes)
}
Ejemplo n.º 10
0
// WriteEnvMapToFile ...
func WriteEnvMapToFile(pth string, envs []models.EnvironmentItemModel) error {
	if pth == "" {
		return errors.New("No path provided")
	}

	envYML, err := generateFormattedYMLForEnvModels(envs)
	if err != nil {
		return err
	}
	bytes, err := yaml.Marshal(envYML)
	if err != nil {
		return err
	}
	return fileutil.WriteBytesToFile(pth, bytes)
}
Ejemplo n.º 11
0
// WriteIntoFileInDir ...
func (model SSHConfigModel) WriteIntoFileInDir(workdirPth string) error {
	if err := model.normalizeAndValidate(); err != nil {
		return err
	}

	configBytes, err := model.serializeIntoJSONBytes()
	if err != nil {
		return err
	}

	if err := fileutil.WriteBytesToFile(fullSSHConfigFilePath(workdirPth), configBytes); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 12
0
func export(c *cli.Context) {
	PrintBitriseHeaderASCIIArt(c.App.Version)

	outfilePth := c.String(OuputPathKey)
	if outfilePth == "" {
		log.Fatalln("No output file path specified!")
	}
	outFormat := c.String(OuputFormatKey)
	if outFormat == "" {
		log.Fatalln("No output file format specified!")
	}

	// Config validation
	bitriseConfig, err := CreateBitriseConfigFromCLIParams(c)
	if err != nil {
		log.Fatalf("Failed to create bitrise cofing, err: %s", err)
	}

	// serialize
	configBytes := []byte{}
	if outFormat == OutputFormatJSON {
		if c.Bool(PrettyFormatKey) {
			configBytes, err = json.MarshalIndent(bitriseConfig, "", "\t")
		} else {
			configBytes, err = json.Marshal(bitriseConfig)
		}
		if err != nil {
			log.Fatalln("Failed to generate JSON: ", err)
		}
	} else if outFormat == OutputFormatYML {
		configBytes, err = yaml.Marshal(bitriseConfig)
		if err != nil {
			log.Fatalln("Failed to generate YAML: ", err)
		}
	} else {
		log.Fatalln("Invalid output format: ", outFormat)
	}

	// write to file
	if err := fileutil.WriteBytesToFile(outfilePth, configBytes); err != nil {
		log.Fatalf("Failed to write to file (%s), error: ", err)
	}

	log.Infoln("Done, saved to path: ", outfilePth)
}
Ejemplo n.º 13
0
func initRelease(c *cli.Context) {
	//
	// Fail if git is not clean
	if exist, err := pathutil.IsPathExists(releaseman.DefaultConfigPth); err != nil {
		log.Fatalf("Failed to check path (%s), error: %#v", releaseman.DefaultConfigPth, err)
	} else if exist {
		if releaseman.IsCIMode {
			log.Fatalf("Release config already exist at (%s)", releaseman.DefaultConfigPth)
		} else {
			ok, err := goinp.AskForBoolWithDefault(fmt.Sprintf("Release config already exist at (%s), would you like to overwrite it?", releaseman.DefaultConfigPth), true)
			if err != nil {
				log.Fatalf("Failed to ask for bool, error: %#v", err)
			} else if !ok {
				log.Fatalln("Create release config aborted")
			}
		}
	}

	releaseConfig, err := collectInitConfigParams(releaseman.Config{}, c)
	if err != nil {
		log.Fatalf("Failed to collect config params, error: %#v", err)
	}
	releaseConfig.Changelog.ContentTemplate = releaseman.ChangelogContentTemplate
	releaseConfig.Changelog.HeaderTemplate = releaseman.ChangelogHeaderTemplate
	releaseConfig.Changelog.FooterTemplate = releaseman.ChangelogFooterTemplate

	//
	// Print config
	releaseConfig.Print(releaseman.FullMode)

	bytes, err := yaml.Marshal(releaseConfig)
	if err != nil {
		log.Fatalf("Failed to marshal config, error: %#v", err)
	}

	if err := fileutil.WriteBytesToFile(releaseman.DefaultConfigPth, bytes); err != nil {
		log.Fatalf("Failed to write config to file, error: %#v", err)
	}
}
Ejemplo n.º 14
0
func create(c *cli.Context) error {
	toolMode := c.Bool(ToolMode)

	share, err := ReadShareSteplibFromFile()
	if err != nil {
		log.Error(err)
		log.Fatalln("You have to start sharing with `stepman share start`, or you can read instructions with `stepman share`")
	}

	// Input validation
	tag := c.String(TagKey)
	if tag == "" {
		log.Fatalln("No Step tag specified")
	}

	gitURI := c.String(GitKey)
	if gitURI == "" {
		log.Fatalln("No Step url specified")
	}

	stepID := c.String(StepIDKEy)
	if stepID == "" {
		stepID = getStepIDFromGit(gitURI)
	}
	if stepID == "" {
		log.Fatalln("No Step id specified")
	}
	r := regexp.MustCompile(`[a-z0-9-]+`)
	if find := r.FindString(stepID); find != stepID {
		log.Fatalln("StepID doesn't conforms to: [a-z0-9-]")
	}

	route, found := stepman.ReadRoute(share.Collection)
	if !found {
		log.Fatalf("No route found for collectionURI (%s)", share.Collection)
	}
	stepDirInSteplib := stepman.GetStepCollectionDirPath(route, stepID, tag)
	stepYMLPathInSteplib := path.Join(stepDirInSteplib, "step.yml")
	if exist, err := pathutil.IsPathExists(stepYMLPathInSteplib); err != nil {
		log.Fatalf("Failed to check step.yml path in steplib, err: %s", err)
	} else if exist {
		log.Warnf("Step already exist in path: %s.", stepDirInSteplib)
		if val, err := goinp.AskForBool("Would you like to overwrite local version of Step?"); err != nil {
			log.Fatalf("Failed to get bool, err: %s", err)
		} else {
			if !val {
				log.Errorln("Unfortunately we can't continue with sharing without an overwrite exist step.yml.")
				log.Fatalln("Please finish your changes, run this command again and allow it to overwrite the exist step.yml!")
			}
		}
	}

	// Clone Step to tmp dir
	tmp, err := pathutil.NormalizedOSTempDirPath("")
	if err != nil {
		log.Fatalf("Failed to get temp directory, err: %s", err)
	}

	log.Infof("Cloning Step from (%s) with tag (%s) to temporary path (%s)", gitURI, tag, tmp)
	if err := cmdex.GitCloneTag(gitURI, tmp, tag); err != nil {
		log.Fatalf("Git clone failed, err: %s", err)
	}

	// Update step.yml
	tmpStepYMLPath := path.Join(tmp, "step.yml")
	bytes, err := fileutil.ReadBytesFromFile(tmpStepYMLPath)
	if err != nil {
		log.Fatalf("Failed to read Step from file, err: %s", err)
	}
	var stepModel models.StepModel
	if err := yaml.Unmarshal(bytes, &stepModel); err != nil {
		log.Fatalf("Failed to unmarchal Step, err: %s", err)
	}

	commit, err := cmdex.GitGetCommitHashOfHEAD(tmp)
	if err != nil {
		log.Fatalf("Failed to get commit hash, err: %s", err)
	}
	stepModel.Source = &models.StepSourceModel{
		Git:    gitURI,
		Commit: commit,
	}
	stepModel.PublishedAt = pointers.NewTimePtr(time.Now())

	// Validate step-yml
	if err := stepModel.Audit(); err != nil {
		log.Fatalf("Failed to validate Step, err: %s", err)
	}
	for _, input := range stepModel.Inputs {
		key, value, err := input.GetKeyValuePair()
		if err != nil {
			log.Fatalf("Failed to get Step input key-value pair, err: %s", err)
		}

		options, err := input.GetOptions()
		if err != nil {
			log.Fatalf("Failed to get Step input (%s) options, err: %s", key, err)
		}

		if len(options.ValueOptions) > 0 && value == "" {
			log.Warn("Step input with 'value_options', should contain default value!")
			log.Fatalf("Missing default value for Step input (%s).", key)
		}
	}
	if strings.Contains(*stepModel.Summary, "\n") {
		log.Warningln("Step summary should be one line!")
	}
	if utf8.RuneCountInString(*stepModel.Summary) > maxSummaryLength {
		log.Warningf("Step summary should contains maximum (%d) characters, actual: (%d)!", maxSummaryLength, utf8.RuneCountInString(*stepModel.Summary))
	}

	// Copy step.yml to steplib
	share.StepID = stepID
	share.StepTag = tag
	if err := WriteShareSteplibToFile(share); err != nil {
		log.Fatalf("Failed to save share steplib to file, err: %s", err)
	}

	log.Info("Step dir in collection:", stepDirInSteplib)
	if exist, err := pathutil.IsPathExists(stepDirInSteplib); err != nil {
		log.Fatalf("Failed to check path (%s), err: %s", stepDirInSteplib, err)
	} else if !exist {
		if err := os.MkdirAll(stepDirInSteplib, 0777); err != nil {
			log.Fatalf("Failed to create path (%s), err: %s", stepDirInSteplib, err)
		}
	}

	log.Infof("Checkout branch: %s", share.ShareBranchName())
	collectionDir := stepman.GetCollectionBaseDirPath(route)
	if err := cmdex.GitCheckout(collectionDir, share.ShareBranchName()); err != nil {
		if err := cmdex.GitCreateAndCheckoutBranch(collectionDir, share.ShareBranchName()); err != nil {
			log.Fatalf("Git failed to create and checkout branch, err: %s", err)
		}
	}

	stepBytes, err := yaml.Marshal(stepModel)
	if err != nil {
		log.Fatalf("Failed to marcshal Step model, err: %s", err)
	}
	if err := fileutil.WriteBytesToFile(stepYMLPathInSteplib, stepBytes); err != nil {
		log.Fatalf("Failed to write Step to file, err: %s", err)
	}

	// Update spec.json
	if err := stepman.ReGenerateStepSpec(route); err != nil {
		log.Fatalf("Failed to re-create steplib, err: %s", err)
	}

	printFinishCreate(share, stepDirInSteplib, toolMode)

	return nil
}
Ejemplo n.º 15
0
func export(c *cli.Context) error {
	// Expand cli.Context
	bitriseConfigBase64Data := c.String(ConfigBase64Key)

	bitriseConfigPath := c.String(ConfigKey)
	deprecatedBitriseConfigPath := c.String(PathKey)
	if bitriseConfigPath == "" && deprecatedBitriseConfigPath != "" {
		log.Warn("'path' key is deprecated, use 'config' instead!")
		bitriseConfigPath = deprecatedBitriseConfigPath
	}

	outfilePth := c.String(OuputPathKey)
	outFormat := c.String(OuputFormatKey)
	prettyFormat := c.Bool(PrettyFormatKey)
	//

	if outfilePth == "" {
		log.Fatal("No output file path specified!")
	}
	if outFormat == "" {
		log.Fatal("No output file format specified!")
	}

	// Config validation
	bitriseConfig, warnings, err := CreateBitriseConfigFromCLIParams(bitriseConfigBase64Data, bitriseConfigPath)
	for _, warning := range warnings {
		log.Warnf("warning: %s", warning)
	}
	if err != nil {
		log.Fatalf("Failed to create bitrise config, error: %s", err)
	}

	// serialize
	configBytes := []byte{}
	if outFormat == output.FormatJSON {
		if prettyFormat {
			configBytes, err = json.MarshalIndent(bitriseConfig, "", "\t")
		} else {
			configBytes, err = json.Marshal(bitriseConfig)
		}
		if err != nil {
			log.Fatalf("Failed to generate config JSON, error: %s", err)
		}
	} else if outFormat == output.FormatYML {
		configBytes, err = yaml.Marshal(bitriseConfig)
		if err != nil {
			log.Fatalf("Failed to generate config YML, error: %s", err)
		}
	} else {
		log.Fatalf("Invalid output format: %s", outFormat)
	}

	// write to file
	if err := fileutil.WriteBytesToFile(outfilePth, configBytes); err != nil {
		log.Fatalf("Failed to write file (%s), error: %s", outfilePth, err)
	}

	log.Infof("Done, saved to path: %s", outfilePth)

	return nil
}
Ejemplo n.º 16
0
func export(c *cli.Context) error {
	// Input validation
	steplibURI := c.String("steplib")
	outputPth := c.String("output")
	exportTypeStr := c.String("export-type")

	if steplibURI == "" {
		return fmt.Errorf("Missing required input: steplib")
	}

	if outputPth == "" {
		return fmt.Errorf("Missing required input: output")
	}

	exportType := exportTypeFull
	if exportTypeStr != "" {
		var err error
		exportType, err = parseExportType(exportTypeStr)
		if err != nil {
			return err
		}
	}

	log.Infof("Exporting StepLib (%s) spec, export-type: %s, output: %s", steplibURI, exportTypeStr, outputPth)

	// Setup StepLib
	if exist, err := stepman.RootExistForCollection(steplibURI); err != nil {
		return fmt.Errorf("Failed to check if setup was done for StepLib, error: %s", err)
	} else if !exist {
		log.Infof("StepLib does not exist, setup...")
		if err := setupSteplib(steplibURI, false); err != nil {
			return fmt.Errorf("Failed to setup StepLib, error: %s", err)
		}
	}

	// Prepare spec
	stepLibSpec, err := stepman.ReadStepSpec(steplibURI)
	if err != nil {
		log.Fatalln("Failed to read StepLib spec, error: %s", err)
	}

	switch exportType {
	case exportTypeMinimal:
		stepLibSpec = convertToMinimalSpec(stepLibSpec)
	case exportTypeLatest:
		stepLibSpec = convertToLatestSpec(stepLibSpec)
	}

	stepLibSpecBytes, err := json.Marshal(stepLibSpec)
	if err != nil {
		return fmt.Errorf("Failed to marshal StepLib, error: %s", err)
	}

	// Export spec
	outputDir := filepath.Dir(outputPth)

	exist, err := pathutil.IsDirExists(outputDir)
	if err != nil {
		return fmt.Errorf("Failed to check if dir (%s) exist, error: %s", outputDir, err)
	}
	if !exist {
		if err := os.MkdirAll(outputDir, 0777); err != nil {
			return fmt.Errorf("Failed to create dir (%s), error: %s", outputDir, err)
		}
	}

	if err := fileutil.WriteBytesToFile(outputPth, stepLibSpecBytes); err != nil {
		return fmt.Errorf("Failed to write StepLib spec to: %s, error: %s", outputPth, err)
	}

	log.Infof("StepLib spec exported to: %s", outputPth)

	return nil
}