// triggerMatchesBuildImageChange identifies whether the image change is equivalent to the trigger
15178
func triggerMatchesBuildImageChange(trigger ImageChangeTrigger, strategyTrigger *ImageChangeTrigger, imageChange *buildv1.ImageChangeTrigger) bool {
	if imageChange == nil {
		return false
	}
	if imageChange.From == nil {
		return strategyTrigger != nil && strategyTrigger.From == trigger.From && strategyTrigger.Namespace == trigger.Namespace
	}
	namespace := imageChange.From.Namespace
	if strategyTrigger != nil {
		namespace = defaultNamespace(namespace, strategyTrigger.Namespace)
	}
	return imageChange.From.Name == trigger.From && namespace == trigger.Namespace
}
499349
func UpdateDeploymentConfigImages(dc *appsv1.DeploymentConfig, tagRetriever trigger.TagRetriever) (*appsv1.DeploymentConfig, bool, error) {
	var updated *appsv1.DeploymentConfig

	// copy the object and reset dc to the copy
	copyObject := func() {
		if updated != nil {
			return
		}
		dc = dc.DeepCopy()
		updated = dc
	}

	for i, t := range dc.Spec.Triggers {
		p := t.ImageChangeParams
		if p == nil || p.From.Kind != "ImageStreamTag" {
			continue
		}
		if !p.Automatic {
			continue
		}

		namespace := p.From.Namespace
		if len(namespace) == 0 {
			namespace = dc.Namespace
		}

		ref, _, ok := tagRetriever.ImageStreamTag(namespace, p.From.Name)
		if !ok && len(p.LastTriggeredImage) == 0 {
			klog.V(4).Infof("trigger %#v in deployment %s is not resolveable", p, dc.Name)
			return nil, false, nil
		}

		if len(ref) == 0 {
			ref = p.LastTriggeredImage
		}

		if p.LastTriggeredImage != ref {
			copyObject()
			p = dc.Spec.Triggers[i].ImageChangeParams
			p.LastTriggeredImage = ref
		}

		for i, c := range dc.Spec.Template.Spec.InitContainers {
			if !namesInclude(p.ContainerNames, c.Name) || c.Image == ref {
				continue
			}
			copyObject()
			container := &dc.Spec.Template.Spec.InitContainers[i]
			container.Image = ref
		}

		for i, c := range dc.Spec.Template.Spec.Containers {
			if !namesInclude(p.ContainerNames, c.Name) || c.Image == ref {
				continue
			}
			copyObject()
			container := &dc.Spec.Template.Spec.Containers[i]
			container.Image = ref
		}
	}
	return updated, true, nil
}
198760
func (w *fakeWatcher) TriggerEvent(op fsnotify.Op, filename string) {
	w.eventHandler(fsnotify.Event{Op: op, Name: filename})
}
978417
func calculateDeploymentConfigTrigger(t appsv1.DeploymentTriggerPolicy, dc *appsv1.DeploymentConfig) []triggerapi.ObjectFieldTrigger {
	if t.ImageChangeParams == nil {
		return nil
	}
	from := t.ImageChangeParams.From
	if from.Kind != "ImageStreamTag" || len(from.Name) == 0 {
		return nil
	}

	var triggers []triggerapi.ObjectFieldTrigger

	// add one trigger per init container and container
	for _, index := range indicesForContainerNames(dc.Spec.Template.Spec.Containers, t.ImageChangeParams.ContainerNames) {
		fieldPath := fmt.Sprintf("spec.template.spec.containers[@name==\"%s\"].image", dc.Spec.Template.Spec.Containers[index].Name)
		triggers = append(triggers, triggerapi.ObjectFieldTrigger{
			From: triggerapi.ObjectReference{
				Name:       from.Name,
				Namespace:  from.Namespace,
				Kind:       from.Kind,
				APIVersion: from.APIVersion,
			},
			FieldPath: fieldPath,
			Paused:    !t.ImageChangeParams.Automatic,
		})
	}
	for _, index := range indicesForContainerNames(dc.Spec.Template.Spec.InitContainers, t.ImageChangeParams.ContainerNames) {
		fieldPath := fmt.Sprintf("spec.template.spec.initContainers[@name==\"%s\"].image", dc.Spec.Template.Spec.InitContainers[index].Name)
		triggers = append(triggers, triggerapi.ObjectFieldTrigger{
			From: triggerapi.ObjectReference{
				Name:       from.Name,
				Namespace:  from.Namespace,
				Kind:       from.Kind,
				APIVersion: from.APIVersion,
			},
			FieldPath: fieldPath,
			Paused:    !t.ImageChangeParams.Automatic,
		})
	}
	return triggers
}
1196216
func (o *TriggersOptions) updateTriggers(triggers *TriggerDefinition) {
	// clear everything
	if o.RemoveAll {
		*triggers = TriggerDefinition{}
		return
	}

	// clear a specific field
	if o.Remove {
		if o.FromConfig {
			triggers.ConfigChange = false
		}
		if len(o.FromImage) > 0 {
			var newTriggers []ImageChangeTrigger
			for _, trigger := range triggers.ImageChange {
				if trigger.From != o.FromImage {
					newTriggers = append(newTriggers, trigger)
				}
			}
			triggers.ImageChange = newTriggers
		}
		if o.FromWebHook != nil && *o.FromWebHook {
			triggers.GenericWebHooks = nil
		}
		if o.FromWebHookAllowEnv != nil && *o.FromWebHookAllowEnv {
			triggers.GenericWebHooks = nil
		}
		if o.FromGitHub != nil && *o.FromGitHub {
			triggers.GitHubWebHooks = nil
		}
		if o.FromGitLab != nil && *o.FromGitLab {
			triggers.GitLabWebHooks = nil
		}
		if o.FromBitbucket != nil && *o.FromBitbucket {
			triggers.BitbucketWebHooks = nil
		}
		return
	}

	// change the automated status
	if o.Reset {
		triggers.ConfigChange = o.Auto
		for i := range triggers.ImageChange {
			triggers.ImageChange[i].Auto = o.Auto
		}
		return
	}

	// change individual elements
	if o.FromConfig {
		triggers.ConfigChange = true
	}
	if len(o.FromImage) > 0 {
		names := strings.Split(o.ContainerNames, ",")
		if len(o.ContainerNames) == 0 {
			names = nil
		}
		found := false
		for i, trigger := range triggers.ImageChange {
			if trigger.From == o.FromImage && trigger.Namespace == o.FromImageNamespace {
				found = true
				triggers.ImageChange[i].Auto = !o.Manual
				triggers.ImageChange[i].Names = names
				break
			}
		}
		if !found {
			triggers.ImageChange = append(triggers.ImageChange, ImageChangeTrigger{
				From:      o.FromImage,
				Namespace: o.FromImageNamespace,
				Auto:      !o.Manual,
				Names:     names,
			})
		}
	}
	if o.FromWebHook != nil && *o.FromWebHook {
		secret := app.GenerateSecret(20)
		triggers.GenericWebHooks = append(triggers.GenericWebHooks,
			buildv1.WebHookTrigger{
				Secret:   secret,
				AllowEnv: false,
			},
		)
	}
	if o.FromWebHookAllowEnv != nil && *o.FromWebHookAllowEnv {
		secret := app.GenerateSecret(20)
		triggers.GenericWebHooks = append(triggers.GenericWebHooks,
			buildv1.WebHookTrigger{
				Secret:   secret,
				AllowEnv: true,
			},
		)
	}
	if o.FromGitHub != nil && *o.FromGitHub {
		secret := app.GenerateSecret(20)
		triggers.GitHubWebHooks = append(triggers.GitHubWebHooks,
			buildv1.WebHookTrigger{
				Secret: secret,
			},
		)
	}
	if o.FromGitLab != nil && *o.FromGitLab {
		secret := app.GenerateSecret(20)
		triggers.GitLabWebHooks = append(triggers.GitLabWebHooks,
			buildv1.WebHookTrigger{
				Secret: secret,
			},
		)
	}
	if o.FromBitbucket != nil && *o.FromBitbucket {
		secret := app.GenerateSecret(20)
		triggers.BitbucketWebHooks = append(triggers.BitbucketWebHooks,
			buildv1.WebHookTrigger{
				Secret: secret,
			},
		)
	}
}
1161014
func retryBuildConfig(obj *unstructured.Unstructured, err error) *unstructured.Unstructured {
	if obj == nil {
		return nil
	}
	triggerTypeWhiteList := map[buildv1.BuildTriggerType]struct{}{
		buildv1.GitHubWebHookBuildTriggerType:    {},
		buildv1.GenericWebHookBuildTriggerType:   {},
		buildv1.ImageChangeBuildTriggerType:      {},
		buildv1.GitLabWebHookBuildTriggerType:    {},
		buildv1.BitbucketWebHookBuildTriggerType: {},
	}
	if build.Kind("BuildConfig") == obj.GroupVersionKind().GroupKind() && isInvalidTriggerError(err) {
		var bc *buildv1.BuildConfig
		err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, bc)
		if err != nil {
			return nil
		}

		triggers := []buildv1.BuildTriggerPolicy{}
		for _, t := range bc.Spec.Triggers {
			if _, inList := triggerTypeWhiteList[t.Type]; inList {
				triggers = append(triggers, t)
			}
		}
		bc.Spec.Triggers = triggers

		retUnstructured, err := runtime.DefaultUnstructuredConverter.ToUnstructured(bc)
		if err != nil {
			return nil
		}
		return &unstructured.Unstructured{Object: retUnstructured}
	}
	return nil
}
403175
func NewSfFbInviteChangeRoleDetails(TargetAssetIndex uint64, OriginalFolderName string) *SfFbInviteChangeRoleDetails {
	s := new(SfFbInviteChangeRoleDetails)
	s.TargetAssetIndex = TargetAssetIndex
	s.OriginalFolderName = OriginalFolderName
	return s
}
718381
func (r *DeploymentConfigReactor) ImageChanged(obj runtime.Object, tagRetriever trigger.TagRetriever) error {
	dc := obj.(*appsv1.DeploymentConfig)
	newDC := dc.DeepCopy()

	updated, resolvable, err := UpdateDeploymentConfigImages(newDC, tagRetriever)
	if err != nil {
		return err
	}
	if !resolvable {
		if klog.V(4) {
			klog.Infof("Ignoring changes to deployment config %s, has unresolved images: %s", dc.Name, printDeploymentTriggers(newDC.Spec.Triggers))
		}
		return nil
	}
	if updated == nil {
		klog.V(4).Infof("Deployment config %s has not changed", dc.Name)
		return nil
	}
	klog.V(4).Infof("Deployment config %s has changed", dc.Name)
	_, err = r.Client.DeploymentConfigs(dc.Namespace).Update(updated)
	return err
}
738423
func TemplateImageForContainer(pod *corev1.PodSpec, triggerFn TriggeredByFunc, containerName string) (TemplateImage, error) {
	for i := range pod.Containers {
		container := &pod.Containers[i]
		if container.Name != containerName {
			continue
		}
		return templateImageForContainer(container, triggerFn)
	}
	for i := range pod.InitContainers {
		container := &pod.InitContainers[i]
		if container.Name != containerName {
			continue
		}
		return templateImageForContainer(container, triggerFn)
	}
	return TemplateImage{}, fmt.Errorf("no container %q found", containerName)
}
159199
func (j *Client) TriggerBuildWithParams(name string, values url.Values) (string, error) {
	//curl -u "dynport:horse battery staple" -d 'SPECS=spec&BRANCH=2.2.3&' https://phrasebuild.wunderscale.com/job/phrase-experimental/buildWithParameters -i
	u := j.Address + "/job/" + name + "/buildWithParameters"
	rsp, err := j.client().PostForm(u, values)
	if err != nil {
		return "", err
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		b, _ := ioutil.ReadAll(rsp.Body)
		return "", fmt.Errorf("got status %s but expected 2x. body=%s", rsp.Status, string(b))
	}
	return rsp.Header.Get("Location"), nil
}
542523
func TriggerEvent(name TriggerEventName, payload interface{}) error {
	// Create plugin input
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	pluginInput := PluginInput{
		PluginInputPayloadKey:      string(payloadBytes),
		PluginInputTriggerEventKey: string(name),
	}

	// Load plugins
	plugins, err := LoadPlugins(string(name))
	if err != nil {
		return err
	}

	// Run plugins
	for _, plugin := range plugins {
		if err := RunPluginByEvent(plugin, pluginInput); err != nil {
			return err
		}
	}

	return nil
}
1241375
func ManifestMatchesImage(image *imageapi.Image, newManifest []byte) (bool, error) {
	dgst, err := godigest.Parse(image.Name)
	if err != nil {
		return false, err
	}
	v := dgst.Verifier()
	var canonical []byte
	switch image.DockerImageManifestMediaType {
	case schema2.MediaTypeManifest:
		var m schema2.DeserializedManifest
		if err := json.Unmarshal(newManifest, &m); err != nil {
			return false, err
		}
		_, canonical, err = m.Payload()
		if err != nil {
			return false, err
		}
	case schema1.MediaTypeManifest, "":
		var m schema1.SignedManifest
		if err := json.Unmarshal(newManifest, &m); err != nil {
			return false, err
		}
		canonical = m.Canonical
	default:
		return false, fmt.Errorf("unsupported manifest mediatype: %s", image.DockerImageManifestMediaType)
	}
	if _, err := v.Write(canonical); err != nil {
		return false, err
	}
	return v.Verified(), nil
}
1252848
func Convert_build_ImageChangeCause_To_v1_ImageChangeCause(in *build.ImageChangeCause, out *v1.ImageChangeCause, s conversion.Scope) error {
	return autoConvert_build_ImageChangeCause_To_v1_ImageChangeCause(in, out, s)
}
1042353
func (t *LaunchTemplate) CheckChanges(a, e, changes *LaunchTemplate) error {
	if e.ImageID == nil {
		return fi.RequiredField("ImageID")
	}
	if e.InstanceType == nil {
		return fi.RequiredField("InstanceType")
	}

	if a != nil {
		if e.Name == nil {
			return fi.RequiredField("Name")
		}
	}
	return nil
}
1320769
func (_ *AttachISO) CheckChanges(a, e, changes *AttachISO) error {
	glog.Info("AttachISO.CheckChanges invoked!")
	return nil
}
632304
func (sc *ServiceCheck) TriggersRestarts() bool {
	return sc.CheckRestart != nil && sc.CheckRestart.Limit > 0
}
1156174
func triggerCheck(c *cli.Context) error {
	warnings := []string{}

	//
	// Expand cli.Context
	var prGlobalFlagPtr *bool
	if c.GlobalIsSet(PRKey) {
		prGlobalFlagPtr = pointers.NewBoolPtr(c.GlobalBool(PRKey))
	}

	triggerPattern := c.String(PatternKey)
	if triggerPattern == "" && len(c.Args()) > 0 {
		triggerPattern = c.Args()[0]
	}

	pushBranch := c.String(PushBranchKey)
	prSourceBranch := c.String(PRSourceBranchKey)
	prTargetBranch := c.String(PRTargetBranchKey)
	tag := c.String(TagKey)

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

	inventoryBase64Data := c.String(InventoryBase64Key)
	inventoryPath := c.String(InventoryKey)

	jsonParams := c.String(JSONParamsKey)
	jsonParamsBase64 := c.String(JSONParamsBase64Key)

	format := c.String(OuputFormatKey)

	triggerParams, err := parseTriggerCheckParams(
		triggerPattern,
		pushBranch, prSourceBranch, prTargetBranch, tag,
		format,
		bitriseConfigPath, bitriseConfigBase64Data,
		inventoryPath, inventoryBase64Data,
		jsonParams, jsonParamsBase64)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to parse trigger check params, err: %s", err), warnings, triggerParams.Format)
	}
	//

	// Inventory validation
	inventoryEnvironments, err := CreateInventoryFromCLIParams(triggerParams.InventoryBase64Data, triggerParams.InventoryPath)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to create inventory, err: %s", err), warnings, triggerParams.Format)
	}

	// Config validation
	bitriseConfig, warns, err := CreateBitriseConfigFromCLIParams(triggerParams.BitriseConfigBase64Data, triggerParams.BitriseConfigPath)
	warnings = append(warnings, warns...)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to create config, err: %s", err), warnings, triggerParams.Format)
	}

	// Format validation
	if triggerParams.Format == "" {
		triggerParams.Format = output.FormatRaw
	} else if !(triggerParams.Format == output.FormatRaw || triggerParams.Format == output.FormatJSON) {
		registerFatal(fmt.Sprintf("Invalid format: %s", triggerParams.Format), warnings, output.FormatJSON)
	}

	// Trigger filter validation
	if triggerParams.TriggerPattern == "" &&
		triggerParams.PushBranch == "" && triggerParams.PRSourceBranch == "" && triggerParams.PRTargetBranch == "" && triggerParams.Tag == "" {
		registerFatal("No trigger pattern nor trigger params specified", warnings, triggerParams.Format)
	}
	//

	//
	// Main
	isPRMode, err := isPRMode(prGlobalFlagPtr, inventoryEnvironments)
	if err != nil {
		registerFatal(fmt.Sprintf("Failed to check  PR mode, err: %s", err), warnings, triggerParams.Format)
	}

	workflowToRunID, err := getWorkflowIDByParamsInCompatibleMode(bitriseConfig.TriggerMap, triggerParams, isPRMode)
	if err != nil {
		registerFatal(err.Error(), warnings, triggerParams.Format)
	}

	triggerModel := map[string]string{
		"workflow": workflowToRunID,
	}

	if triggerParams.TriggerPattern != "" {
		triggerModel["pattern"] = triggerParams.TriggerPattern
	} else {
		if triggerParams.PushBranch != "" {
			triggerModel["push-branch"] = triggerParams.PushBranch
		} else if triggerParams.PRSourceBranch != "" || triggerParams.PRTargetBranch != "" {
			if triggerParams.PRSourceBranch != "" {
				triggerModel["pr-source-branch"] = triggerParams.PRSourceBranch
			}
			if triggerParams.PRTargetBranch != "" {
				triggerModel["pr-target-branch"] = triggerParams.PRTargetBranch
			}
		} else if triggerParams.Tag != "" {
			triggerModel["tag"] = triggerParams.Tag
		}
	}

	switch triggerParams.Format {
	case output.FormatRaw:
		msg := ""
		for key, value := range triggerModel {
			if key == "workflow" {
				msg = msg + fmt.Sprintf("-> %s", colorstring.Blue(value))
			} else {
				msg = fmt.Sprintf("%s: %s ", key, value) + msg
			}
		}
		fmt.Println(msg)
		break
	case output.FormatJSON:
		bytes, err := json.Marshal(triggerModel)
		if err != nil {
			registerFatal(fmt.Sprintf("Failed to parse trigger model, err: %s", err), warnings, triggerParams.Format)
		}

		fmt.Println(string(bytes))
		break
	default:
		registerFatal(fmt.Sprintf("Invalid format: %s", triggerParams.Format), warnings, output.FormatJSON)
	}
	//

	return nil
}