// SetCharm changes the charm for the application.
545320
func (a *Application) SetCharm(cfg SetCharmConfig) (err error) {
	defer errors.DeferredAnnotatef(
		&err, "cannot upgrade application %q to charm %q", a, cfg.Charm,
	)
	if cfg.Charm.Meta().Subordinate != a.doc.Subordinate {
		return errors.Errorf("cannot change an application's subordinacy")
	}
	currentCharm, err := a.st.Charm(a.doc.CharmURL)
	if err != nil {
		return errors.Trace(err)
	}
	if cfg.Charm.Meta().Deployment != currentCharm.Meta().Deployment {
		if currentCharm.Meta().Deployment == nil ||
			cfg.Charm.Meta().Deployment.DeploymentType != currentCharm.Meta().Deployment.DeploymentType {
			return errors.New("cannot change a charm's deployment type")
		}
	}
	// For old style charms written for only one series, we still retain
	// this check. Newer charms written for multi-series have a URL
	// with series = "".
	if cfg.Charm.URL().Series != "" {
		if cfg.Charm.URL().Series != a.doc.Series {
			return errors.Errorf("cannot change an application's series")
		}
	} else if !cfg.ForceSeries {
		supported := false
		for _, oneSeries := range cfg.Charm.Meta().Series {
			if oneSeries == a.doc.Series {
				supported = true
				break
			}
		}
		if !supported {
			supportedSeries := "no series"
			if len(cfg.Charm.Meta().Series) > 0 {
				supportedSeries = strings.Join(cfg.Charm.Meta().Series, ", ")
			}
			return errors.Errorf("only these series are supported: %v", supportedSeries)
		}
	} else {
		// Even with forceSeries=true, we do not allow a charm to be used which is for
		// a different OS. This assumes the charm declares it has supported series which
		// we can check for OS compatibility. Otherwise, we just accept the series supplied.
		currentOS, err := series.GetOSFromSeries(a.doc.Series)
		if err != nil {
			// We don't expect an error here but there's not much we can
			// do to recover.
			return err
		}
		supportedOS := false
		supportedSeries := cfg.Charm.Meta().Series
		for _, chSeries := range supportedSeries {
			charmSeriesOS, err := series.GetOSFromSeries(chSeries)
			if err != nil {
				return nil
			}
			if currentOS == charmSeriesOS {
				supportedOS = true
				break
			}
		}
		if !supportedOS && len(supportedSeries) > 0 {
			return errors.Errorf("OS %q not supported by charm", currentOS)
		}
	}

	updatedSettings, err := cfg.Charm.Config().ValidateSettings(cfg.ConfigSettings)
	if err != nil {
		return errors.Annotate(err, "validating config settings")
	}

	// we don't need to check that this is a charm.LXDProfiler, as we can
	// state that the function exists.
	if profile := cfg.Charm.LXDProfile(); profile != nil {
		// Validate the config devices, to ensure we don't apply an invalid
		// profile, if we know it's never going to work.
		if err := profile.ValidateConfigDevices(); err != nil && !cfg.Force {
			return errors.Annotate(err, "validating lxd profile")
		}
	}

	var newCharmModifiedVersion int
	channel := string(cfg.Channel)
	acopy := &Application{a.st, a.doc}
	buildTxn := func(attempt int) ([]txn.Op, error) {
		a := acopy
		if attempt > 0 {
			if err := a.Refresh(); err != nil {
				return nil, errors.Trace(err)
			}
		}

		// NOTE: We're explicitly allowing SetCharm to succeed
		// when the application is Dying, because application/charm
		// upgrades should still be allowed to apply to dying
		// applications and units, so that bugs in departed/broken
		// hooks can be addressed at runtime.
		if a.Life() == Dead {
			return nil, ErrDead
		}

		// Record the current value of charmModifiedVersion, so we can
		// set the value on the method receiver's in-memory document
		// structure. We increment the version only when we change the
		// charm URL.
		newCharmModifiedVersion = a.doc.CharmModifiedVersion

		ops := []txn.Op{{
			C:  applicationsC,
			Id: a.doc.DocID,
			Assert: append(notDeadDoc, bson.DocElem{
				"charmmodifiedversion", a.doc.CharmModifiedVersion,
			}),
		}}

		if a.doc.CharmURL.String() == cfg.Charm.URL().String() {
			// Charm URL already set; just update the force flag and channel.
			ops = append(ops, txn.Op{
				C:  applicationsC,
				Id: a.doc.DocID,
				Update: bson.D{{"$set", bson.D{
					{"cs-channel", channel},
					{"forcecharm", cfg.ForceUnits},
				}}},
			})
		} else {
			chng, err := a.changeCharmOps(
				cfg.Charm,
				channel,
				updatedSettings,
				cfg.ForceUnits,
				cfg.ResourceIDs,
				cfg.StorageConstraints,
			)
			if err != nil {
				return nil, errors.Trace(err)
			}
			ops = append(ops, chng...)
			newCharmModifiedVersion++
		}

		return ops, nil
	}
	if err := a.st.db().Run(buildTxn); err != nil {
		return err
	}
	a.doc.CharmURL = cfg.Charm.URL()
	a.doc.Channel = channel
	a.doc.ForceCharm = cfg.ForceUnits
	a.doc.CharmModifiedVersion = newCharmModifiedVersion
	return nil
}
747571
func (r Repository) AddCharm(id *charm.URL, channel params.Channel, force bool) error {
	withRevision := r.addRevision(id)
	alreadyAdded := r.added[string(channel)]

	for _, charm := range alreadyAdded {
		if *withRevision == charm {
			return nil
			// TODO(tsm) check expected behaviour
			//
			// if force {
			// 	return nil
			// } else {
			// 	return errors.NewAlreadyExists(errors.NewErr("%v already added in channel %v", id, channel))
			// }
		}
	}
	r.added[string(channel)] = append(alreadyAdded, *withRevision)
	return nil
}
1099746
func (s *UpdateItemInput) SetKey(v map[string]*AttributeValue) *UpdateItemInput {
	s.Key = v
	return s
}
582952
func (s *UpdateAppOutput) SetApp(v *App) *UpdateAppOutput {
	s.App = v
	return s
}
953370
func (h *bundleHandler) addCharm(change *bundlechanges.AddCharmChange) error {
	if h.dryRun {
		return nil
	}
	id := change.Id()
	p := change.Params
	// First attempt to interpret as a local path.
	if h.isLocalCharm(p.Charm) {
		charmPath := p.Charm
		if !filepath.IsAbs(charmPath) {
			charmPath = filepath.Join(h.bundleDir, charmPath)
		}

		series := p.Series
		if series == "" {
			series = h.data.Series
		}
		ch, curl, err := charmrepo.NewCharmAtPath(charmPath, series)
		if err != nil && !os.IsNotExist(err) {
			return errors.Annotatef(err, "cannot deploy local charm at %q", charmPath)
		}
		if err == nil {
			if err := lxdprofile.ValidateLXDProfile(lxdCharmProfiler{
				Charm: ch,
			}); err != nil {
				return errors.Annotatef(err, "cannot deploy local charm at %q", charmPath)
			}
			if curl, err = h.api.AddLocalCharm(curl, ch, false); err != nil {
				return err
			}
			logger.Debugf("added charm %s", curl)
			h.results[id] = curl.String()
			return nil
		}
	}

	// Not a local charm, so grab from the store.
	ch, err := charm.ParseURL(p.Charm)
	if err != nil {
		return errors.Trace(err)
	}

	url, channel, _, err := resolveCharm(h.api.ResolveWithChannel, ch)
	if err != nil {
		return errors.Annotatef(err, "cannot resolve URL %q", p.Charm)
	}
	if url.Series == "bundle" {
		return errors.Errorf("expected charm URL, got bundle URL %q", p.Charm)
	}
	var macaroon *macaroon.Macaroon
	url, macaroon, err = addCharmFromURL(h.api, url, channel, false)
	if err != nil {
		return errors.Annotatef(err, "cannot add charm %q", p.Charm)
	}
	logger.Debugf("added charm %s", url)
	h.results[id] = url.String()
	h.macaroons[url] = macaroon
	h.channels[url] = channel
	return nil
}
1368376
func (m *Model) updateCharm(ch CharmChange, rm *residentManager) {
	m.mu.Lock()

	charm, found := m.charms[ch.CharmURL]
	if !found {
		charm = newCharm(m.metrics, m.hub, rm.new())
		m.charms[ch.CharmURL] = charm
	}
	charm.setDetails(ch)

	m.mu.Unlock()
}
997111
func (mr *MockMutaterMachineMockRecorder) SetCharmProfiles(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCharmProfiles", reflect.TypeOf((*MockMutaterMachine)(nil).SetCharmProfiles), arg0)
}
570972
func (context *BaseContext) SetString(key string, value string) {
	context.userData[key] = value
}
277628
func (u *UUID) SetString(str string) error {
	/* NOTE: Duplicate of ReadBytes, with different method signature, to
	   prevent unnecessary copying of memory due to string <-> []byte conversion */
	i := 0
	x := 0
	c := len(str)

	for x < c {
		a := hexchar2byte[str[x]]
		if a == 255 {
			// Invalid char, skip
			x++

			continue
		}

		// We need to perform this check after the attempted hex-read in case
		// we have trailing "}" characters
		if i >= 16 {
			return &ErrTooLong{x, i, c}
		}
		if x+1 >= c {
			// Not enough to scan
			return &ErrTooShort{x, i, c}
		}

		b := hexchar2byte[str[x+1]]
		if b == 255 {
			// Uneven hexadecimal byte
			return &ErrUneven{x, i, c}
		}

		u[i] = (a << 4) | b

		x += 2
		i++
	}

	if i != 16 {
		// Can only be too short here
		return &ErrTooShort{x, i, c}
	}

	return nil
}
591189
func (c *Client) SetScheme(scheme string) *Client {
	if !IsStringEmpty(scheme) {
		c.scheme = scheme
	}

	return c
}
1151925
func (bb *Builder) SetType(t string) *Builder {
	bb.m["camliType"] = t
	return bb
}
1211251
func (c *upgradeCharmCommand) addCharm(
	charmAdder CharmAdder,
	charmRepo *charmrepo.CharmStore,
	config *config.Config,
	oldURL *charm.URL,
	charmRef string,
	deployedSeries string,
	force bool,
) (charmstore.CharmID, *macaroon.Macaroon, error) {
	var id charmstore.CharmID
	// Charm may have been supplied via a path reference. If so, build a
	// local charm URL from the deployed series.
	ch, newURL, err := charmrepo.NewCharmAtPathForceSeries(charmRef, deployedSeries, c.ForceSeries)
	if err == nil {
		newName := ch.Meta().Name
		if newName != oldURL.Name {
			return id, nil, errors.Errorf("cannot upgrade %q to %q", oldURL.Name, newName)
		}
		addedURL, err := charmAdder.AddLocalCharm(newURL, ch, force)
		id.URL = addedURL
		return id, nil, err
	}
	if _, ok := err.(*charmrepo.NotFoundError); ok {
		return id, nil, errors.Errorf("no charm found at %q", charmRef)
	}
	// If we get a "not exists" or invalid path error then we attempt to interpret
	// the supplied charm reference as a URL below, otherwise we return the error.
	if err != os.ErrNotExist && !charmrepo.IsInvalidPathError(err) {
		return id, nil, err
	}

	refURL, err := charm.ParseURL(charmRef)
	if err != nil {
		return id, nil, errors.Trace(err)
	}

	// Charm has been supplied as a URL so we resolve and deploy using the store.
	newURL, channel, supportedSeries, err := c.ResolveCharm(charmRepo.ResolveWithChannel, refURL)
	if err != nil {
		return id, nil, errors.Trace(err)
	}
	id.Channel = channel
	_, seriesSupportedErr := charm.SeriesForCharm(deployedSeries, supportedSeries)
	if !c.ForceSeries && deployedSeries != "" && newURL.Series == "" && seriesSupportedErr != nil {
		series := []string{"no series"}
		if len(supportedSeries) > 0 {
			series = supportedSeries
		}
		return id, nil, errors.Errorf(
			"cannot upgrade from single series %q charm to a charm supporting %q. Use --force-series to override.",
			deployedSeries, series,
		)
	}
	// If no explicit revision was set with either SwitchURL
	// or Revision flags, discover the latest.
	if *newURL == *oldURL {
		if refURL.Revision != -1 {
			return id, nil, errors.Errorf("already running specified charm %q", newURL)
		}
		// No point in trying to upgrade a charm store charm when
		// we just determined that's the latest revision
		// available.
		return id, nil, errors.Errorf("already running latest charm %q", newURL)
	}

	curl, csMac, err := addCharmFromURL(charmAdder, newURL, channel, force)
	if err != nil {
		return id, nil, errors.Trace(err)
	}
	id.URL = curl
	return id, csMac, nil
}
968740
func (s *SegmentGroup) SetType(v string) *SegmentGroup {
	s.Type = &v
	return s
}
54048
func (s *GetAppOutput) SetApp(v *App) *GetAppOutput {
	s.App = v
	return s
}
727715
func (c *Captcha) SetFont(paths ...string) error {
	for _, v := range paths {
		if erro := c.AddFont(v); erro != nil {
			return erro
		}
	}
	return nil
}
1050018
func (s *SimpleEmailPart) SetCharset(v string) *SimpleEmailPart {
	s.Charset = &v
	return s
}
21443
func (opc *operationCallbacks) SetCurrentCharm(charmURL *corecharm.URL) error {
	return opc.u.unit.SetCharmURL(charmURL)
}