// Apply use the V2 API to create/update the application settings and
// eventually uploads the application bits.
//
// If multiple buildpacks are being applied to the application, the V3 API is
// used to set those buildpacks.
7996
func (actor Actor) Apply(config ApplicationConfig, progressBar ProgressBar) (<-chan ApplicationConfig, <-chan Event, <-chan Warnings, <-chan error) {
	configStream := make(chan ApplicationConfig)
	eventStream := make(chan Event)
	warningsStream := make(chan Warnings)
	errorStream := make(chan error)

	go func() {
		log.Debug("starting apply go routine")
		defer close(configStream)
		defer close(eventStream)
		defer close(warningsStream)
		defer close(errorStream)

		var event Event
		var warnings Warnings
		var err error

		eventStream <- SettingUpApplication
		if config.UpdatingApplication() {
			config, event, warnings, err = actor.UpdateApplication(config)
		} else {
			config, event, warnings, err = actor.CreateApplication(config)
		}

		warningsStream <- warnings
		if err != nil {
			errorStream <- err
			return
		}
		eventStream <- event
		log.Debugf("desired application: %#v", config.DesiredApplication)

		if config.NoRoute {
			if len(config.CurrentRoutes) > 0 {
				eventStream <- UnmappingRoutes
				config, warnings, err = actor.UnmapRoutes(config)
				warningsStream <- warnings
				if err != nil {
					errorStream <- err
					return
				}
			}
		} else {
			eventStream <- CreatingAndMappingRoutes

			var createdRoutes bool
			config, createdRoutes, warnings, err = actor.CreateRoutes(config)
			warningsStream <- warnings
			if err != nil {
				errorStream <- err
				return
			}
			if createdRoutes {
				log.Debugf("updated desired routes: %#v", config.DesiredRoutes)
				eventStream <- CreatedRoutes
			}

			var boundRoutes bool
			config, boundRoutes, warnings, err = actor.MapRoutes(config)
			warningsStream <- warnings
			if err != nil {
				errorStream <- err
				return
			}
			if boundRoutes {
				log.Debugf("updated desired routes: %#v", config.DesiredRoutes)
				eventStream <- BoundRoutes
			}
		}

		if len(config.CurrentServices) != len(config.DesiredServices) {
			eventStream <- ConfiguringServices
			config, _, warnings, err = actor.BindServices(config)
			warningsStream <- warnings
			if err != nil {
				errorStream <- err
				return
			}

			log.Debugf("bound desired services: %#v", config.DesiredServices)
			eventStream <- BoundServices
		}

		if config.DropletPath != "" {
			for count := 0; count < PushRetries; count++ {
				warnings, err = actor.UploadDroplet(config, config.DropletPath, progressBar, eventStream)
				warningsStream <- warnings
				if _, ok := err.(ccerror.PipeSeekError); ok {
					eventStream <- RetryUpload
				} else {
					break
				}
			}

			if err != nil {
				if e, ok := err.(ccerror.PipeSeekError); ok {
					errorStream <- actionerror.UploadFailedError{Err: e.Err}
				} else {
					errorStream <- err
				}
				return
			}
		} else if config.DesiredApplication.DockerImage == "" {
			eventStream <- ResourceMatching
			config, warnings = actor.SetMatchedResources(config)
			warningsStream <- warnings

			if len(config.UnmatchedResources) > 0 {
				var archivePath string
				archivePath, err = actor.CreateArchive(config)
				if err != nil {
					errorStream <- err
					os.RemoveAll(archivePath)
					return
				}
				eventStream <- CreatingArchive
				defer os.RemoveAll(archivePath)

				for count := 0; count < PushRetries; count++ {
					warnings, err = actor.UploadPackageWithArchive(config, archivePath, progressBar, eventStream)
					warningsStream <- warnings
					if _, ok := err.(ccerror.PipeSeekError); ok {
						eventStream <- RetryUpload
					} else {
						break
					}
				}

				if err != nil {
					if e, ok := err.(ccerror.PipeSeekError); ok {
						errorStream <- actionerror.UploadFailedError{Err: e.Err}
					} else {
						errorStream <- err
					}
					return
				}
			} else {
				eventStream <- UploadingApplication
				warnings, err = actor.UploadPackage(config)
				warningsStream <- warnings
				if err != nil {
					errorStream <- err
					return
				}
			}
		} else {
			log.WithField("docker_image", config.DesiredApplication.DockerImage).Debug("skipping file upload")
		}

		configStream <- config

		log.Debug("completed apply")
		eventStream <- Complete
	}()

	return configStream, eventStream, warningsStream, errorStream
}
1093794
func (f RedirectPolicyFunc) Apply(req *http.Request, via []*http.Request) error {
	return f(req, via)
}
925470
func (f *GenericFlag) Apply(set *flag.FlagSet) {
	f.set = set
	f.GenericFlag.Apply(set)
}
718607
func (o groupResourceOverrides) Apply(config *storagebackend.Config, options *StorageCodecConfig) {
	if len(o.etcdLocation) > 0 {
		config.Transport.ServerList = o.etcdLocation
	}
	if len(o.etcdPrefix) > 0 {
		config.Prefix = o.etcdPrefix
	}

	if len(o.mediaType) > 0 {
		options.StorageMediaType = o.mediaType
	}
	if o.serializer != nil {
		options.StorageSerializer = o.serializer
	}
	if o.encoderDecoratorFn != nil {
		options.EncoderDecoratorFn = o.encoderDecoratorFn
	}
	if o.decoderDecoratorFn != nil {
		options.DecoderDecoratorFn = o.decoderDecoratorFn
	}
	if o.transformer != nil {
		config.Transformer = o.transformer
	}
	if o.disablePaging {
		config.Paging = false
	}
}
1221970
func (gfg *gofiguration) apply(parent *gofiguration) error {
	gfg.parent = parent

	if parent == nil {
		defer gfg.cleanupSources()

		err := gfg.initSources()
		if err != nil {
			return err
		}
	} else {
		parent.children = append(parent.children, gfg)
	}

	err := gfg.registerFields()
	if err != nil {
		return err
	}

	if parent == nil {
		return gfg.populateStruct()
	}

	return nil
}
740768
func (c *CORS) Apply(next web.HandlerFunc) web.HandlerFunc {
	if len(c.AllowOrigins) == 0 {
		c.AllowOrigins = []string{"*"}
	}
	if len(c.AllowMethods) == 0 {
		c.AllowMethods = []string{http.MethodGet, http.MethodPost, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodDelete}
	}

	allowMethods := strings.Join(c.AllowMethods, ",")
	allowHeaders := strings.Join(c.AllowHeaders, ",")
	exposeHeaders := strings.Join(c.ExposeHeaders, ",")
	maxAge := strconv.Itoa(c.MaxAge)

	return func(ctx web.Context) error {
		r := ctx.Request()
		w := ctx.Response()
		origin := r.Header.Get(web.HeaderOrigin)
		if origin == "" {
			return next(ctx)
		}

		// Check allowed origins
		var allowOrigin string
		for _, o := range c.AllowOrigins {
			if o == "*" || o == origin {
				allowOrigin = o
				break
			}
		}

		// Simple request
		if r.Method != http.MethodOptions {
			w.Header().Add(web.HeaderVary, web.HeaderOrigin)
			w.Header().Set(web.HeaderAccessControlAllowOrigin, allowOrigin)
			if c.AllowCredentials {
				w.Header().Set(web.HeaderAccessControlAllowCredentials, "true")
			}
			if exposeHeaders != "" {
				w.Header().Set(web.HeaderAccessControlExposeHeaders, exposeHeaders)
			}
			return next(ctx)
		}

		// Preflight request
		w.Header().Add(web.HeaderVary, web.HeaderOrigin)
		w.Header().Add(web.HeaderVary, web.HeaderAccessControlRequestMethod)
		w.Header().Add(web.HeaderVary, web.HeaderAccessControlRequestHeaders)
		w.Header().Set(web.HeaderAccessControlAllowOrigin, allowOrigin)
		w.Header().Set(web.HeaderAccessControlAllowMethods, allowMethods)
		if c.AllowCredentials {
			w.Header().Set(web.HeaderAccessControlAllowCredentials, "true")
		}
		if allowHeaders != "" {
			w.Header().Set(web.HeaderAccessControlAllowHeaders, allowHeaders)
		} else {
			h := r.Header.Get(web.HeaderAccessControlRequestHeaders)
			if h != "" {
				w.Header().Set(web.HeaderAccessControlAllowHeaders, h)
			}
		}
		if c.MaxAge > 0 {
			w.Header().Set(web.HeaderAccessControlMaxAge, maxAge)
		}
		return ctx.Status(http.StatusNoContent).Empty()
	}
}
430611
func (c *applications) Update(application *v1alpha1.Application) (result *v1alpha1.Application, err error) {
	result = &v1alpha1.Application{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("applications").
		Name(application.Name).
		Body(application).
		Do().
		Into(result)
	return
}
407134
func (f *FieldManager) Apply(liveObj runtime.Object, patch []byte, fieldManager string, force bool) (runtime.Object, error) {
	// If the object doesn't have metadata, apply isn't allowed.
	if _, err := meta.Accessor(liveObj); err != nil {
		return nil, fmt.Errorf("couldn't get accessor: %v", err)
	}

	managed, err := internal.DecodeObjectManagedFields(liveObj)
	if err != nil {
		return nil, fmt.Errorf("failed to decode managed fields: %v", err)
	}
	// Check that the patch object has the same version as the live object
	patchObj := &unstructured.Unstructured{Object: map[string]interface{}{}}

	if err := yaml.Unmarshal(patch, &patchObj.Object); err != nil {
		return nil, fmt.Errorf("error decoding YAML: %v", err)
	}
	if patchObj.GetAPIVersion() != f.groupVersion.String() {
		return nil,
			errors.NewBadRequest(
				fmt.Sprintf("Incorrect version specified in apply patch. "+
					"Specified patch version: %s, expected: %s",
					patchObj.GetAPIVersion(), f.groupVersion.String()))
	}

	liveObjVersioned, err := f.toVersioned(liveObj)
	if err != nil {
		return nil, fmt.Errorf("failed to convert live object to proper version: %v", err)
	}
	internal.RemoveObjectManagedFields(liveObjVersioned)

	patchObjTyped, err := f.typeConverter.YAMLToTyped(patch)
	if err != nil {
		return nil, fmt.Errorf("failed to create typed patch object: %v", err)
	}
	liveObjTyped, err := f.typeConverter.ObjectToTyped(liveObjVersioned)
	if err != nil {
		return nil, fmt.Errorf("failed to create typed live object: %v", err)
	}
	manager, err := f.buildManagerInfo(fieldManager, metav1.ManagedFieldsOperationApply)
	if err != nil {
		return nil, fmt.Errorf("failed to build manager identifier: %v", err)
	}

	apiVersion := fieldpath.APIVersion(f.groupVersion.String())
	newObjTyped, managed, err := f.updater.Apply(liveObjTyped, patchObjTyped, apiVersion, managed, manager, force)
	if err != nil {
		if conflicts, ok := err.(merge.Conflicts); ok {
			return nil, internal.NewConflictError(conflicts)
		}
		return nil, err
	}
	managed = f.stripFields(managed, manager)

	newObj, err := f.typeConverter.TypedToObject(newObjTyped)
	if err != nil {
		return nil, fmt.Errorf("failed to convert new typed object to object: %v", err)
	}

	if err := internal.EncodeObjectManagedFields(newObj, managed); err != nil {
		return nil, fmt.Errorf("failed to encode managed fields: %v", err)
	}

	newObjVersioned, err := f.toVersioned(newObj)
	if err != nil {
		return nil, fmt.Errorf("failed to convert new object to proper version: %v", err)
	}
	f.objectDefaulter.Default(newObjVersioned)

	newObjUnversioned, err := f.toUnversioned(newObjVersioned)
	if err != nil {
		return nil, fmt.Errorf("failed to convert to unversioned: %v", err)
	}
	return newObjUnversioned, nil
}
1055718
func (p *CopyPropagator) Apply(query ast.Body) (result ast.Body) {

	uf, ok := makeDisjointSets(p.livevars, query)
	if !ok {
		return query
	}

	// Compute set of vars that appear in the head of refs in the query. If a var
	// is dereferenced, we cannot plug it with a constant value so the constant on
	// the union-find root must be unset (e.g., [1][0] is not legal.)
	headvars := ast.NewVarSet()
	ast.WalkRefs(query, func(x ast.Ref) bool {
		if v, ok := x[0].Value.(ast.Var); ok {
			if root, ok := uf.Find(v); ok {
				root.constant = nil
				headvars.Add(root.key)
			} else {
				headvars.Add(v)
			}
		}
		return false
	})

	bindings := map[ast.Var]*binding{}

	for _, expr := range query {

		// Deep copy the expr as it may be mutated below. The caller that is running
		// copy propagation may hold references to the expr.
		expr = expr.Copy()

		pctx := &plugContext{
			bindings: bindings,
			uf:       uf,
			negated:  expr.Negated,
			headvars: headvars,
		}

		if p.plugBindings(pctx, expr) {
			if p.updateBindings(pctx, expr) {
				result.Append(expr)
			}
		}
	}

	// Run post-processing step on the query to ensure that all live vars are bound
	// in the result. The plugging that happens above substitutes all vars in the
	// same set with the root.
	//
	// This step should run before the next step to prevent unnecessary bindings
	// from being added to the result. For example:
	//
	// - Given the following result: <empty>
	// - Given the following bindings: x/input.x and y/input
	// - Given the following liveset: {x}
	//
	// If this step were to run AFTER the following step, the output would be:
	//
	//	x = input.x; y = input
	//
	// Even though y = input is not required.
	for _, v := range p.sorted {
		if root, ok := uf.Find(v); ok {
			if root.constant != nil {
				result.Append(ast.Equality.Expr(ast.NewTerm(v), root.constant))
			} else if b, ok := bindings[root.key]; ok {
				result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(b.v)))
			} else if root.key != v {
				result.Append(ast.Equality.Expr(ast.NewTerm(v), ast.NewTerm(root.key)))
			}
		}
	}

	// Run post-processing step on query to ensure that all killed exprs are
	// accounted for. If an expr is killed but the binding is never used, the query
	// must still include the expr. For example, given the query 'input.x = a' and
	// an empty livevar set, the result must include the ref input.x otherwise the
	// query could be satisfied without input.x being defined. When exprs are
	// killed we initialize the binding counter to zero and then increment it each
	// time the binding is substituted. if the binding was never substituted it
	// means the binding value must be added back into the query.
	for _, b := range sortbindings(bindings) {
		if !b.containedIn(result) {
			result.Append(ast.Equality.Expr(ast.NewTerm(b.k), ast.NewTerm(b.v)))
		}
	}

	if p.ensureNonEmptyBody && len(result) == 0 {
		result = append(result, ast.NewExpr(ast.BooleanTerm(true)))
	}

	return result
}
439860
func (s *Logging) Apply(c Config) error {
	err := s.SetFormat(c.Format)
	if err != nil {
		return err
	}

	if c.LogSpec == "" {
		c.LogSpec = os.Getenv("FABRIC_LOGGING_SPEC")
	}
	if c.LogSpec == "" {
		c.LogSpec = defaultLevel.String()
	}

	err = s.LoggerLevels.ActivateSpec(c.LogSpec)
	if err != nil {
		return err
	}

	if c.Writer == nil {
		c.Writer = os.Stderr
	}
	s.SetWriter(c.Writer)

	var formatter logging.Formatter
	switch s.Encoding() {
	case JSON, LOGFMT:
		formatter = SetFormat(defaultFormat)
	default:
		formatter = SetFormat(c.Format)
	}

	InitBackend(formatter, c.Writer)

	return nil
}
982249
func Apply(manifest string) error {
	// We copy the manifest to a temp file because it is likely e.g. an s3 URL, which kubectl can't read
	data, err := vfs.Context.ReadFile(manifest)
	if err != nil {
		return fmt.Errorf("error reading manifest: %v", err)
	}

	tmpDir, err := ioutil.TempDir("", "channel")
	if err != nil {
		return fmt.Errorf("error creating temp dir: %v", err)
	}

	defer func() {
		if err := os.RemoveAll(tmpDir); err != nil {
			glog.Warningf("error deleting temp dir %q: %v", tmpDir, err)
		}
	}()

	localManifestFile := path.Join(tmpDir, "manifest.yaml")
	if err := ioutil.WriteFile(localManifestFile, data, 0600); err != nil {
		return fmt.Errorf("error writing temp file: %v", err)
	}

	_, err = execKubectl("apply", "-f", localManifestFile)
	return err
}
1025262
func (f *PropertyFilter) apply(ctx *Context, change types.ObjectUpdate) types.ObjectUpdate {
	parents := make(map[string]bool)
	set := change.ChangeSet
	change.ChangeSet = nil

	for i, p := range set {
		if f.matches(ctx, change.Obj, &p) {
			if p.Name != set[i].Name {
				// update matches a parent field from the spec.
				if parents[p.Name] {
					continue // only return 1 instance of the parent
				}
				parents[p.Name] = true
			}
			change.ChangeSet = append(change.ChangeSet, p)
		}
	}

	return change
}
882719
func (c *configuration) apply(t transition) {
	logf("Applying %v", t)
	w1 := int(c.stackValue(1))
	w2 := int(c.stackValue(0))

	if t.Move == Left {
		c.AddArc(w2, w1, t.DependencyType)
		c.removeSecondTopStack()
	} else if t.Move == Right {
		c.AddArc(w1, w2, t.DependencyType)
		c.removeTopStack()
	} else {
		c.shift()
	}
}
945616
func (d *InstanceDiff) Apply(attrs map[string]string, schema *configschema.Block) (map[string]string, error) {
	// We always build a new value here, even if the given diff is "empty",
	// because we might be planning to create a new instance that happens
	// to have no attributes set, and so we want to produce an empty object
	// rather than just echoing back the null old value.
	if attrs == nil {
		attrs = map[string]string{}
	}

	// Rather applying the diff to mutate the attrs, we'll copy new values into
	// here to avoid the possibility of leaving stale values.
	result := map[string]string{}

	if d.Destroy || d.DestroyDeposed || d.DestroyTainted {
		return result, nil
	}

	return d.applyBlockDiff(nil, attrs, schema)
}
286910
func (g *Git) Apply(patch string) *command.Model {
	return g.command("apply", "--index", patch)
}
1302292
func (f StoreOpt) Apply(store *Store) error {
	if f != nil {
		return f(store)
	}
	return nil
}
1365175
func (u *VariableUpdate) Apply(m *Variable) error {
	if u.Name != "" {
		m.Name = u.Name
	}

	if u.Selected != nil {
		m.Selected = u.Selected
	}

	if u.Arguments != nil {
		m.Arguments = u.Arguments
	}

	if u.Description != "" {
		m.Description = u.Description
	}

	return nil
}