• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang hcl.Parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/hashicorp/hcl.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: loadVarFile

func loadVarFile(rawPath string) (map[string]string, error) {
	path, err := homedir.Expand(rawPath)
	if err != nil {
		return nil, fmt.Errorf(
			"Error expanding path: %s", err)
	}

	// Read the HCL file and prepare for parsing
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf(
			"Error reading %s: %s", path, err)
	}

	// Parse it
	obj, err := hcl.Parse(string(d))
	if err != nil {
		return nil, fmt.Errorf(
			"Error parsing %s: %s", path, err)
	}

	var result map[string]string
	if err := hcl.DecodeObject(&result, obj); err != nil {
		return nil, err
	}

	return result, nil
}
开发者ID:EZTABLE,项目名称:terraform,代码行数:28,代码来源:flag_var.go


示例2: LoadSSHHelperConfig

// LoadSSHHelperConfig loads ssh-helper's configuration from the file and populates the corresponding
// in-memory structure.
//
// Vault address is a required parameter.
// Mount point defaults to "ssh".
func LoadSSHHelperConfig(path string) (*SSHHelperConfig, error) {
	var config SSHHelperConfig
	contents, err := ioutil.ReadFile(path)
	if !os.IsNotExist(err) {
		obj, err := hcl.Parse(string(contents))
		if err != nil {
			return nil, err
		}

		if err := hcl.DecodeObject(&config, obj); err != nil {
			return nil, err
		}
	} else {
		return nil, err
	}

	if config.VaultAddr == "" {
		return nil, fmt.Errorf("config missing vault_addr")
	}
	if config.SSHMountPoint == "" {
		config.SSHMountPoint = SSHHelperDefaultMountPoint
	}

	return &config, nil
}
开发者ID:sepiroth887,项目名称:vault,代码行数:30,代码来源:ssh_agent.go


示例3: Parse

// Parse parses the detector config from the given io.Reader.
//
// Due to current internal limitations, the entire contents of the
// io.Reader will be copied into memory first before parsing.
func Parse(r io.Reader) (*Config, error) {
	// Copy the reader into an in-memory buffer first since HCL requires it.
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, r); err != nil {
		return nil, err
	}

	// Parse the buffer
	obj, err := hcl.Parse(buf.String())
	if err != nil {
		return nil, fmt.Errorf("error parsing: %s", err)
	}
	buf.Reset()

	var result Config

	// Parse the detects
	if o := obj.Get("detect", false); o != nil {
		if err := parseDetect(&result, o); err != nil {
			return nil, fmt.Errorf("error parsing 'import': %s", err)
		}
	}

	return &result, nil
}
开发者ID:nvartolomei,项目名称:otto,代码行数:29,代码来源:parse.go


示例4: ParseConfig

// ParseConfig parses the config from the given io.Reader.
//
// Due to current internal limitations, the entire contents of the
// io.Reader will be copied into memory first before parsing.
func ParseConfig(r io.Reader) (*Config, error) {
	// Copy the reader into an in-memory buffer first since HCL requires it.
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, r); err != nil {
		return nil, err
	}

	// Parse the buffer
	root, err := hcl.Parse(buf.String())
	if err != nil {
		return nil, fmt.Errorf("error parsing: %s", err)
	}
	buf.Reset()

	// Top-level item should be a list
	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, fmt.Errorf("error parsing: root should be an object")
	}

	var config Config
	if err := parseConfig(&config, list); err != nil {
		return nil, fmt.Errorf("error parsing 'config': %v", err)
	}

	return &config, nil
}
开发者ID:iverberk,项目名称:nomad,代码行数:31,代码来源:config_parse.go


示例5: Parse

// Parse parses the job spec from the given io.Reader.
//
// Due to current internal limitations, the entire contents of the
// io.Reader will be copied into memory first before parsing.
func Parse(r io.Reader) (*structs.Job, error) {
	// Copy the reader into an in-memory buffer first since HCL requires it.
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, r); err != nil {
		return nil, err
	}

	// Parse the buffer
	root, err := hcl.Parse(buf.String())
	if err != nil {
		return nil, fmt.Errorf("error parsing: %s", err)
	}
	buf.Reset()

	// Top-level item should be a list
	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, fmt.Errorf("error parsing: root should be an object")
	}

	var job structs.Job

	// Parse the job out
	matches := list.Filter("job")
	if len(matches.Items) == 0 {
		return nil, fmt.Errorf("'job' stanza not found")
	}
	if err := parseJob(&job, matches); err != nil {
		return nil, fmt.Errorf("error parsing 'job': %s", err)
	}

	return &job, nil
}
开发者ID:fanyeren,项目名称:nomad,代码行数:37,代码来源:parse.go


示例6: loadKVFile

func loadKVFile(rawPath string) (map[string]interface{}, error) {
	path, err := homedir.Expand(rawPath)
	if err != nil {
		return nil, fmt.Errorf(
			"Error expanding path: %s", err)
	}

	// Read the HCL file and prepare for parsing
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf(
			"Error reading %s: %s", path, err)
	}

	// Parse it
	obj, err := hcl.Parse(string(d))
	if err != nil {
		return nil, fmt.Errorf(
			"Error parsing %s: %s", path, err)
	}

	var result map[string]interface{}
	if err := hcl.DecodeObject(&result, obj); err != nil {
		return nil, fmt.Errorf(
			"Error decoding Terraform vars file: %s\n\n"+
				"The vars file should be in the format of `key = \"value\"`.\n"+
				"Decoding errors are usually caused by an invalid format.",
			err)
	}

	return result, nil
}
开发者ID:partamonov,项目名称:terraform,代码行数:32,代码来源:flag_kv.go


示例7: Parse

// Parse parses the job spec from the given io.Reader.
//
// Due to current internal limitations, the entire contents of the
// io.Reader will be copied into memory first before parsing.
func Parse(r io.Reader) (*structs.Job, error) {
	// Copy the reader into an in-memory buffer first since HCL requires it.
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, r); err != nil {
		return nil, err
	}

	// Parse the buffer
	obj, err := hcl.Parse(buf.String())
	if err != nil {
		return nil, fmt.Errorf("error parsing: %s", err)
	}
	buf.Reset()

	var job structs.Job

	// Parse the job out
	jobO := obj.Get("job", false)
	if jobO == nil {
		return nil, fmt.Errorf("'job' stanza not found")
	}
	if err := parseJob(&job, jobO); err != nil {
		return nil, fmt.Errorf("error parsing 'job': %s", err)
	}

	return &job, nil
}
开发者ID:rbramwell,项目名称:nomad,代码行数:31,代码来源:parse.go


示例8: LoadConfig

// LoadConfig reads the configuration from the given path. If path is
// empty, then the default path will be used, or the environment variable
// if set.
func LoadConfig(path string) (*Config, error) {
	if path == "" {
		path = DefaultConfigPath
	}
	if v := os.Getenv(ConfigPathEnv); v != "" {
		path = v
	}

	path, err := homedir.Expand(path)
	if err != nil {
		return nil, fmt.Errorf("Error expanding config path: %s", err)
	}

	var config Config
	contents, err := ioutil.ReadFile(path)
	if !os.IsNotExist(err) {
		if err != nil {
			return nil, err
		}

		obj, err := hcl.Parse(string(contents))
		if err != nil {
			return nil, err
		}

		if err := hcl.DecodeObject(&config, obj); err != nil {
			return nil, err
		}
	}

	return &config, nil
}
开发者ID:vincentaubert,项目名称:vault,代码行数:35,代码来源:config.go


示例9: ParseSSHHelperConfig

// ParseSSHHelperConfig parses the given contents as a string for the SSHHelper
// configuration.
func ParseSSHHelperConfig(contents string) (*SSHHelperConfig, error) {
	root, err := hcl.Parse(string(contents))
	if err != nil {
		return nil, fmt.Errorf("ssh_helper: error parsing config: %s", err)
	}

	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, fmt.Errorf("ssh_helper: error parsing config: file doesn't contain a root object")
	}

	valid := []string{
		"vault_addr",
		"ssh_mount_point",
		"ca_cert",
		"ca_path",
		"allowed_cidr_list",
		"allowed_roles",
		"tls_skip_verify",
	}
	if err := checkHCLKeys(list, valid); err != nil {
		return nil, multierror.Prefix(err, "ssh_helper:")
	}

	var c SSHHelperConfig
	c.SSHMountPoint = SSHHelperDefaultMountPoint
	if err := hcl.DecodeObject(&c, list); err != nil {
		return nil, multierror.Prefix(err, "ssh_helper:")
	}

	if c.VaultAddr == "" {
		return nil, fmt.Errorf("ssh_helper: missing config 'vault_addr'")
	}
	return &c, nil
}
开发者ID:achanda,项目名称:nomad,代码行数:37,代码来源:ssh_agent.go


示例10: ParseClusterFromFile

// ParseClusterFromFile reads a cluster from file
func ParseClusterFromFile(path string) (*Cluster, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, maskAny(err)
	}
	// Parse the input
	root, err := hcl.Parse(string(data))
	if err != nil {
		return nil, maskAny(err)
	}
	// Top-level item should be a list
	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, errgo.New("error parsing: root should be an object")
	}
	matches := list.Filter("cluster")
	if len(matches.Items) == 0 {
		return nil, errgo.New("'cluster' stanza not found")
	}

	// Parse hcl into Cluster
	cluster := &Cluster{}
	if err := cluster.parse(matches); err != nil {
		return nil, maskAny(err)
	}
	cluster.setDefaults()

	// Validate the cluster
	if err := cluster.validate(); err != nil {
		return nil, maskAny(err)
	}

	return cluster, nil
}
开发者ID:pulcy,项目名称:quark,代码行数:35,代码来源:parse.go


示例11: main

func main() {
	for i, arg := range os.Args {
		if i == 0 {
			continue
		}
		search := arg
		if info, err := os.Stat(arg); err == nil && info.IsDir() {
			search = fmt.Sprintf("%s/*.tf", arg)
		}
		files, err := filepath.Glob(search)
		if err != nil {
			colorstring.Printf("[red]Error finding files: %s", err)
		}
		for _, filename := range files {
			fmt.Printf("Checking %s ... ", filename)
			file, err := ioutil.ReadFile(filename)
			if err != nil {
				colorstring.Printf("[red]Error reading file: %s\n", err)
				break
			}
			_, err = hcl.Parse(string(file))
			if err != nil {
				colorstring.Printf("[red]Error parsing file: %s\n", err)
				break
			}
			colorstring.Printf("[green]OK!\n")
		}
	}

}
开发者ID:derekdowling,项目名称:hcl-lint,代码行数:30,代码来源:lint.go


示例12: ParseConfig

// ParseConfig parses the given configuration as a string.
func ParseConfig(contents string) (*DefaultConfig, error) {
	root, err := hcl.Parse(contents)
	if err != nil {
		return nil, err
	}

	// Top-level item should be the object list
	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, fmt.Errorf("Failed to parse config: does not contain a root object")
	}

	valid := []string{
		"token_helper",
	}
	if err := checkHCLKeys(list, valid); err != nil {
		return nil, err
	}

	var c DefaultConfig
	if err := hcl.DecodeObject(&c, list); err != nil {
		return nil, err
	}
	return &c, nil
}
开发者ID:hashbrowncipher,项目名称:vault,代码行数:26,代码来源:config.go


示例13: Parse

// Parse parses the detector config from the given io.Reader.
//
// Due to current internal limitations, the entire contents of the
// io.Reader will be copied into memory first before parsing.
func Parse(r io.Reader) (*Config, error) {
	// Copy the reader into an in-memory buffer first since HCL requires it.
	var buf bytes.Buffer
	if _, err := io.Copy(&buf, r); err != nil {
		return nil, err
	}

	// Parse the buffer
	root, err := hcl.Parse(buf.String())
	if err != nil {
		return nil, fmt.Errorf("error parsing: %s", err)
	}
	buf.Reset()

	// Top-level item should be the object list
	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, fmt.Errorf("error parsing: file doesn't contain a root object")
	}

	var result Config

	// Parse the detects
	if o := list.Filter("detect"); len(o.Items) > 0 {
		if err := parseDetect(&result, o); err != nil {
			return nil, fmt.Errorf("error parsing 'import': %s", err)
		}
	}

	return &result, nil
}
开发者ID:mbrodala,项目名称:otto,代码行数:35,代码来源:parse.go


示例14: LoadConfigFile

// LoadConfigFile loads the configuration from the given file.
func LoadConfigFile(path string) (*Config, error) {
	// Read the file
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	// Parse!
	obj, err := hcl.Parse(string(d))
	if err != nil {
		return nil, err
	}

	// Start building the result
	var result Config
	if err := hcl.DecodeObject(&result, obj); err != nil {
		return nil, err
	}

	if objs := obj.Get("listener", false); objs != nil {
		result.Listeners, err = loadListeners(objs)
		if err != nil {
			return nil, err
		}
	}
	if objs := obj.Get("backend", false); objs != nil {
		result.Backend, err = loadBackend(objs)
		if err != nil {
			return nil, err
		}
	}

	return &result, nil
}
开发者ID:worldspawn,项目名称:vault,代码行数:35,代码来源:config.go


示例15: parseJob

// ParseJob takes input from a given reader and parses it into a Job.
func parseJob(input []byte, jf *jobFunctions) (*Job, error) {
	// Create a template, add the function map, and parse the text.
	tmpl, err := template.New("job").Funcs(jf.Functions()).Parse(string(input))
	if err != nil {
		return nil, maskAny(err)
	}

	// Run the template to verify the output.
	buffer := &bytes.Buffer{}
	err = tmpl.Execute(buffer, jf.Options())
	if err != nil {
		return nil, maskAny(err)
	}

	// Parse the input
	root, err := hcl.Parse(buffer.String())
	if err != nil {
		return nil, maskAny(err)
	}
	// Top-level item should be a list
	list, ok := root.Node.(*ast.ObjectList)
	if !ok {
		return nil, errgo.New("error parsing: root should be an object")
	}

	// Parse hcl into Job
	job := &Job{}
	matches := list.Filter("job")
	if len(matches.Items) == 0 {
		return nil, maskAny(errgo.WithCausef(nil, ValidationError, "'job' stanza not found"))
	}
	if err := job.parse(matches); err != nil {
		return nil, maskAny(err)
	}

	// Link internal structures
	job.prelink()

	// Set defaults
	job.setDefaults(jf.cluster)

	// Replace variables
	if err := job.replaceVariables(); err != nil {
		return nil, maskAny(err)
	}

	// Sort internal structures and make final links
	job.link()

	// Optimize job for cluster
	job.optimizeFor(jf.cluster)

	// Validate the job
	if err := job.Validate(); err != nil {
		return nil, maskAny(err)
	}

	return job, nil
}
开发者ID:pulcy,项目名称:j2,代码行数:60,代码来源:parse.go


示例16: LoadConfigFile

// LoadConfigFile loads the configuration from the given file.
func LoadConfigFile(path string) (*Config, error) {
	// Read the file
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	// Parse!
	obj, err := hcl.Parse(string(d))
	if err != nil {
		return nil, err
	}

	// Start building the result
	var result Config
	if err := hcl.DecodeObject(&result, obj); err != nil {
		return nil, err
	}

	if result.MaxLeaseDurationRaw != "" {
		if result.MaxLeaseDuration, err = time.ParseDuration(result.MaxLeaseDurationRaw); err != nil {
			return nil, err
		}
	}
	if result.DefaultLeaseDurationRaw != "" {
		if result.DefaultLeaseDuration, err = time.ParseDuration(result.DefaultLeaseDurationRaw); err != nil {
			return nil, err
		}
	}

	if objs := obj.Get("listener", false); objs != nil {
		result.Listeners, err = loadListeners(objs)
		if err != nil {
			return nil, err
		}
	}
	if objs := obj.Get("backend", false); objs != nil {
		result.Backend, err = loadBackend(objs)
		if err != nil {
			return nil, err
		}
	}

	// A little hacky but upgrades the old stats config directives to the new way
	if result.Telemetry == nil {
		statsdAddr := obj.Get("statsd_addr", false)
		statsiteAddr := obj.Get("statsite_addr", false)

		if statsdAddr != nil || statsiteAddr != nil {
			result.Telemetry = &Telemetry{
				StatsdAddr:   getString(statsdAddr),
				StatsiteAddr: getString(statsiteAddr),
			}
		}
	}

	return &result, nil
}
开发者ID:kgutwin,项目名称:vault,代码行数:59,代码来源:config.go


示例17: ParseConfig

func ParseConfig(configBytes []byte, filename string) (*Config, error) {
	rawConfigFile, err := hcl.Parse(string(configBytes))
	if err != nil {
		return nil, err
	}

	rawConfig := rawConfigFile.Node
	return NewConfigFromHCL(rawConfig.(*ast.ObjectList), filename)
}
开发者ID:apparentlymart,项目名称:padstone,代码行数:9,代码来源:config.go


示例18: unmarshallConfigReader

func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
	buf := new(bytes.Buffer)
	buf.ReadFrom(in)

	switch strings.ToLower(configType) {
	case "yaml", "yml":
		if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "json":
		if err := json.Unmarshal(buf.Bytes(), &c); err != nil {
			return ConfigParseError{err}
		}

	case "hcl":
		obj, err := hcl.Parse(string(buf.Bytes()))
		if err != nil {
			return ConfigParseError{err}
		}
		if err = hcl.DecodeObject(&c, obj); err != nil {
			return ConfigParseError{err}
		}

	case "toml":
		tree, err := toml.LoadReader(buf)
		if err != nil {
			return ConfigParseError{err}
		}
		tmap := tree.ToMap()
		for k, v := range tmap {
			c[k] = v
		}

	case "properties", "props", "prop":
		var p *properties.Properties
		var err error
		if p, err = properties.Load(buf.Bytes(), properties.UTF8); err != nil {
			return ConfigParseError{err}
		}
		for _, key := range p.Keys() {
			value, _ := p.Get(key)
			// recursively build nested maps
			path := strings.Split(key, ".")
			lastKey := strings.ToLower(path[len(path)-1])
			deepestMap := deepSearch(c, path[0:len(path)-1])
			// set innermost value
			deepestMap[lastKey] = value
		}
	}

	insensitiviseMap(c)
	return nil
}
开发者ID:ovh,项目名称:tatcli,代码行数:54,代码来源:util.go


示例19: parseVarFlagAsHCL

// parseVarFlagAsHCL parses the value of a single variable as would have been specified
// on the command line via -var or in an environment variable named TF_VAR_x, where x is
// the name of the variable. In order to get around the restriction of HCL requiring a
// top level object, we prepend a sentinel key, decode the user-specified value as its
// value and pull the value back out of the resulting map.
func parseVarFlagAsHCL(input string) (string, interface{}, error) {
	idx := strings.Index(input, "=")
	if idx == -1 {
		return "", nil, fmt.Errorf("No '=' value in variable: %s", input)
	}
	probablyName := input[0:idx]

	parsed, err := hcl.Parse(input)
	if err != nil {
		value := input[idx+1:]

		// If it didn't parse as HCL, we check if it doesn't match our
		// whitelist of TF-accepted HCL types for inputs. If not, then
		// we let it through as a raw string.
		trimmed := strings.TrimSpace(value)
		if !varFlagHCLRe.MatchString(trimmed) {
			return probablyName, value, nil
		}

		// This covers flags of the form `foo=bar` which is not valid HCL
		// At this point, probablyName is actually the name, and the remainder
		// of the expression after the equals sign is the value.
		if regexp.MustCompile(`Unknown token: \d+:\d+ IDENT`).Match([]byte(err.Error())) {
			return probablyName, value, nil
		}

		return "", nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL: %s", probablyName, input, err)
	}

	var decoded map[string]interface{}
	if hcl.DecodeObject(&decoded, parsed); err != nil {
		return "", nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL: %s", probablyName, input, err)
	}

	// Cover cases such as key=
	if len(decoded) == 0 {
		return probablyName, "", nil
	}

	if len(decoded) > 1 {
		return "", nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. Only one value may be specified.", probablyName, input)
	}

	for k, v := range decoded {
		return k, v, nil
	}

	// Should be unreachable
	return "", nil, fmt.Errorf("No value for variable: %s", input)
}
开发者ID:partamonov,项目名称:terraform,代码行数:55,代码来源:flag_kv.go


示例20: LoadJSON

// LoadJSON loads a single Terraform configuration from a given JSON document.
//
// The document must be a complete Terraform configuration. This function will
// NOT try to load any additional modules so only the given document is loaded.
func LoadJSON(raw json.RawMessage) (*Config, error) {
	obj, err := hcl.Parse(string(raw))
	if err != nil {
		return nil, fmt.Errorf(
			"Error parsing JSON document as HCL: %s", err)
	}

	// Start building the result
	hclConfig := &hclConfigurable{
		Object: obj,
	}

	return hclConfig.Config()
}
开发者ID:rgl,项目名称:terraform,代码行数:18,代码来源:loader.go



注:本文中的github.com/hashicorp/hcl.Parse函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang hcl.Object类代码示例发布时间:2022-05-23
下一篇:
Golang hcl.DecodeObject函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap