// loadLocalsHcl recurses into the given HCL object turns it into
// a list of locals.
184476
func loadLocalsHcl(list *ast.ObjectList) ([]*Local, error) {

	result := make([]*Local, 0, len(list.Items))

	for _, block := range list.Items {
		if len(block.Keys) > 0 {
			return nil, fmt.Errorf(
				"locals block at %s should not have label %q",
				block.Pos(), block.Keys[0].Token.Value(),
			)
		}

		blockObj, ok := block.Val.(*ast.ObjectType)
		if !ok {
			return nil, fmt.Errorf("locals value at %s should be a block", block.Val.Pos())
		}

		// blockObj now contains directly our local decls
		for _, item := range blockObj.List.Items {
			if len(item.Keys) != 1 {
				return nil, fmt.Errorf("local declaration at %s may not be a block", item.Val.Pos())
			}

			// By the time we get here there can only be one item left, but
			// we'll decode into a map anyway because it's a convenient way
			// to extract both the key and the value robustly.
			kv := map[string]interface{}{}
			hcl.DecodeObject(&kv, item)
			for k, v := range kv {
				rawConfig, err := NewRawConfig(map[string]interface{}{
					"value": v,
				})

				if err != nil {
					return nil, fmt.Errorf(
						"error parsing local value %q at %s: %s",
						k, item.Val.Pos(), err,
					)
				}

				result = append(result, &Local{
					Name:      k,
					RawConfig: rawConfig,
				})
			}
		}
	}

	return result, nil
}
1300601
func LoadGlobalVars(ctx sessionctx.Context, varNames []string) error {
	if sctx, ok := ctx.(sqlexec.RestrictedSQLExecutor); ok {
		nameList := ""
		for i, name := range varNames {
			if i > 0 {
				nameList += ", "
			}
			nameList += fmt.Sprintf("'%s'", name)
		}
		sql := fmt.Sprintf(loadGlobalVarsSQL, nameList)
		rows, _, err := sctx.ExecRestrictedSQL(ctx, sql)
		if err != nil {
			return errors.Trace(err)
		}
		for _, row := range rows {
			varName := row.GetString(0)
			varValue := row.GetString(1)
			variable.SetLocalSystemVar(varName, varValue)
		}
	}
	return nil
}
1242832
func (lc *LightChain) loadLastState() error {
	if head := rawdb.ReadHeadHeaderHash(lc.chainDb); head == (common.Hash{}) {
		// Corrupt or empty database, init from scratch
		lc.Reset()
	} else {
		if header := lc.GetHeaderByHash(head); header != nil {
			lc.hc.SetCurrentHeader(header)
		}
	}

	// Issue a status log and return
	header := lc.hc.CurrentHeader()
	headerTd := lc.GetTd(header.Hash(), header.Number.Uint64())
	log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(header.Time), 0)))

	return nil
}
1216634
func (e *executor) mapperLocal(ctx context.Context, shards []uint64, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) {
	span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapperLocal")
	defer span.Finish()

	ch := make(chan mapResponse, len(shards))

	for _, shard := range shards {
		go func(shard uint64) {
			result, err := mapFn(shard)

			// Return response to the channel.
			select {
			case <-ctx.Done():
			case ch <- mapResponse{result: result, err: err}:
			}
		}(shard)
	}

	// Reduce results
	var maxShard int
	var result interface{}
	for {
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case resp := <-ch:
			if resp.err != nil {
				return nil, resp.err
			}
			result = reduceFn(result, resp.result)
			maxShard++
		}

		// Exit once all shards are processed.
		if maxShard == len(shards) {
			return result, nil
		}
	}
}
282167
func loadProvidersHcl(list *ast.ObjectList) ([]*ProviderConfig, error) {
	if err := assertAllBlocksHaveNames("provider", list); err != nil {
		return nil, err
	}

	list = list.Children()
	if len(list.Items) == 0 {
		return nil, nil
	}

	// Go through each object and turn it into an actual result.
	result := make([]*ProviderConfig, 0, len(list.Items))
	for _, item := range list.Items {
		n := item.Keys[0].Token.Value().(string)

		var listVal *ast.ObjectList
		if ot, ok := item.Val.(*ast.ObjectType); ok {
			listVal = ot.List
		} else {
			return nil, fmt.Errorf("module '%s': should be an object", n)
		}

		var config map[string]interface{}
		if err := hcl.DecodeObject(&config, item.Val); err != nil {
			return nil, err
		}

		delete(config, "alias")
		delete(config, "version")

		rawConfig, err := NewRawConfig(config)
		if err != nil {
			return nil, fmt.Errorf(
				"Error reading config for provider config %s: %s",
				n,
				err)
		}

		// If we have an alias field, then add those in
		var alias string
		if a := listVal.Filter("alias"); len(a.Items) > 0 {
			err := hcl.DecodeObject(&alias, a.Items[0].Val)
			if err != nil {
				return nil, fmt.Errorf(
					"Error reading alias for provider[%s]: %s",
					n,
					err)
			}
		}

		// If we have a version field then extract it
		var version string
		if a := listVal.Filter("version"); len(a.Items) > 0 {
			err := hcl.DecodeObject(&version, a.Items[0].Val)
			if err != nil {
				return nil, fmt.Errorf(
					"Error reading version for provider[%s]: %s",
					n,
					err)
			}
		}

		result = append(result, &ProviderConfig{
			Name:      n,
			Alias:     alias,
			Version:   version,
			RawConfig: rawConfig,
		})
	}

	return result, nil
}
81757
func AddLocalCharmSequences(pool *StatePool) error {
	st := pool.SystemState()
	charmsColl, closer := st.db().GetRawCollection(charmsC)
	defer closer()

	query := bson.M{
		"url": bson.M{"$regex": "^local:"},
	}
	var docs []bson.M
	err := charmsColl.Find(query).Select(bson.M{
		"_id":  1,
		"life": 1,
	}).All(&docs)
	if err != nil {
		return errors.Trace(err)
	}

	// model UUID -> charm URL base -> max revision
	maxRevs := make(map[string]map[string]int)
	var deadIds []string
	for _, doc := range docs {
		id, ok := doc["_id"].(string)
		if !ok {
			upgradesLogger.Errorf("invalid charm id: %v", doc["_id"])
			continue
		}
		modelUUID, urlStr, ok := splitDocID(id)
		if !ok {
			upgradesLogger.Errorf("unable to split charm _id: %v", id)
			continue
		}
		url, err := charm.ParseURL(urlStr)
		if err != nil {
			upgradesLogger.Errorf("unable to parse charm URL: %v", err)
			continue
		}

		if _, exists := maxRevs[modelUUID]; !exists {
			maxRevs[modelUUID] = make(map[string]int)
		}

		baseURL := url.WithRevision(-1).String()
		curRev := maxRevs[modelUUID][baseURL]
		if url.Revision > curRev {
			maxRevs[modelUUID][baseURL] = url.Revision
		}

		if life, ok := doc["life"].(int); !ok {
			upgradesLogger.Errorf("invalid life for charm: %s", id)
			continue
		} else if life == int(Dead) {
			deadIds = append(deadIds, id)
		}

	}

	sequences, closer := st.db().GetRawCollection(sequenceC)
	defer closer()
	for modelUUID, modelRevs := range maxRevs {
		for baseURL, maxRevision := range modelRevs {
			name := charmRevSeqName(baseURL)
			updater := newDbSeqUpdater(sequences, modelUUID, name)
			err := updater.ensure(maxRevision + 1)
			if err != nil {
				return errors.Annotatef(err, "setting sequence %s", name)
			}
		}

	}

	// Remove dead charm documents
	var ops []txn.Op
	for _, id := range deadIds {
		ops = append(ops, txn.Op{
			C:      charmsC,
			Id:     id,
			Remove: true,
		})
	}
	err = st.runRawTransaction(ops)
	return errors.Annotate(err, "removing dead charms")
}
642472
func (u URL) IsLocal() bool {
	return u.Type == URLTypeLocal || (u.Type == URLTypeURL && u.URL.Scheme == "file" && u.URL.Opaque == "")
}
967315
func (s *IndicesGetMappingService) Local(local bool) *IndicesGetMappingService {
	s.local = &local
	return s
}
88020
func (api *LocalClient) Load(name string) (*host.Host, error) {
	h, err := api.Filestore.Load(name)
	if err != nil {
		return nil, errors.Wrap(err, "filestore")
	}

	var def registry.DriverDef
	if def, err = registry.Driver(h.DriverName); err != nil {
		return nil, err
	} else if !def.Builtin || def.DriverCreator == nil {
		return api.legacyClient.Load(name)
	}

	h.Driver = def.DriverCreator()
	return h, json.Unmarshal(h.RawDriver, h.Driver)
}
980979
func loadSalt(id string) ([keySize]byte, error) {

	var salt [keySize]byte

	saltFile := fmt.Sprintf(saltSuffixFormat, id)
	if keyFileExists(saltFile) {
		return readKey(saltFile, keysFolderPrefixFormat)
	}

	// generate the random salt
	salt, err := generateSalt()
	if err != nil {
		return salt, err
	}

	// write the salt to the file with its prefix
	if err := writeKey(saltFile, keysFolderPrefixFormat, salt[:]); err != nil {
		return salt, err
	}

	// return the salt and no error
	return salt, nil
}
482729
func (bs *baseVCSSource) updateLocal(ctx context.Context) error {
	err := bs.repo.fetch(ctx)

	if err != nil {
		return unwrapVcsErr(err)
	}
	return nil
}
421577
func (s *IndicesExistsTypeService) Local(local bool) *IndicesExistsTypeService {
	s.local = &local
	return s
}
655921
func (s *SnapshotGetRepositoryService) Local(local bool) *SnapshotGetRepositoryService {
	s.local = &local
	return s
}
806250
func InitializeLocalClient(client *client.Client) {
	managerLock.Lock()
	defer managerLock.Unlock()
	manager[local] = &zclient{
		client:          client,
		connectionsLock: sync.RWMutex{},
		connections:     make(map[string]*zconn),
	}
}
826162
func FromLocal(fname string) (string, error) {
	var b bytes.Buffer

	fileExists, _ := exists(fname)
	if !fileExists {
		return "", fmt.Errorf("File does not exist\n")
	}

	file, err := os.Open(fname)
	if err != nil {
		return "", fmt.Errorf("Error opening file\n")
	}

	_, err = b.ReadFrom(file)
	if err != nil {
		return "", fmt.Errorf("Error reading file to buffer\n")
	}

	return FromBuffer(b), nil
}
1003932
func (r Repository) AddLocalCharm(id *charm.URL, details charm.Charm, force bool) (*charm.URL, error) {
	return id, r.AddCharm(id, params.NoChannel, force)
}
485852
func NewLocalContainerFS(path string) ContainerFS {
	return &local{
		path:       path,
		Driver:     driver.LocalDriver,
		PathDriver: pathdriver.LocalPathDriver,
	}
}