本文整理汇总了Golang中github.com/hashicorp/hcl.Decode函数的典型用法代码示例。如果您正苦于以下问题:Golang Decode函数的具体用法?Golang Decode怎么用?Golang Decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Decode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Parse
// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
// Decode the rules
p := &Policy{Raw: rules}
if err := hcl.Decode(p, rules); err != nil {
return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
}
// Validate the path policy
for _, pp := range p.Paths {
// Strip the glob character if found
if strings.HasSuffix(pp.Prefix, "*") {
pp.Prefix = strings.TrimSuffix(pp.Prefix, "*")
pp.Glob = true
}
// Check the policy is valid
switch pp.Policy {
case PathPolicyDeny:
case PathPolicyRead:
case PathPolicyWrite:
case PathPolicySudo:
default:
return nil, fmt.Errorf("Invalid path policy: %#v", pp)
}
}
return p, nil
}
示例2: LoadServices
func LoadServices(root string) (d []Config, err error) {
files, _ := filepath.Glob(root + "/*.hcl")
for _, file := range files {
data, err := readFile(file)
if err != nil {
return nil, err
}
var deploy ServiceFile
err = hcl.Decode(&deploy, data)
if err != nil {
return nil, err
}
for i, service := range deploy.Services {
for key, value := range service.RawArtifact {
value["type"] = key
deploy.Services[i].Artifact = value
}
}
d = append(d, deploy.Services...)
}
return
}
示例3: applyConfigFile
func applyConfigFile(options *Options, filePath string) error {
filePath = expandHomeDir(filePath)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return err
}
fileString := []byte{}
log.Printf("Loading config file at: %s", filePath)
fileString, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
config := make(map[string]interface{})
hcl.Decode(&config, string(fileString))
o := structs.New(options)
for _, name := range o.Names() {
configName := strings.ToLower(strings.Join(camelcase.Split(name), "_"))
if val, ok := config[configName]; ok {
field, ok := o.FieldOk(name)
if !ok {
return errors.New("No such field: " + name)
}
err := field.Set(val)
if err != nil {
return err
}
}
}
return nil
}
示例4: Load
//Load provides loading of configuration file
func Load(path string, item interface{}) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
switch checkPath(path) {
case jsontype:
err := json.Unmarshal([]byte(data), item)
if err != nil {
return err
}
return nil
case yamltype:
err := yaml.Unmarshal([]byte(data), item)
if err != nil {
return err
}
return nil
case hcltype:
err := hcl.Decode(item, string(data))
if err != nil {
return err
}
return nil
default:
return fmt.Errorf("Failed to load: This type is unknown")
}
}
示例5: Parse
// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
// Decode the rules
p := &Policy{}
if rules == "" {
// Hot path for empty rules
return p, nil
}
if err := hcl.Decode(p, rules); err != nil {
return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
}
// Validate the key policy
for _, kp := range p.Keys {
switch kp.Policy {
case KeyPolicyDeny:
case KeyPolicyRead:
case KeyPolicyWrite:
default:
return nil, fmt.Errorf("Invalid key policy: %#v", kp)
}
}
// Validate the service policy
for _, sp := range p.Services {
switch sp.Policy {
case ServicePolicyDeny:
case ServicePolicyRead:
case ServicePolicyWrite:
default:
return nil, fmt.Errorf("Invalid service policy: %#v", sp)
}
}
// Validate the user event policies
for _, ep := range p.Events {
switch ep.Policy {
case EventPolicyRead:
case EventPolicyWrite:
case EventPolicyDeny:
default:
return nil, fmt.Errorf("Invalid event policy: %#v", ep)
}
}
// Validate the keyring policy
switch p.Keyring {
case KeyringPolicyRead:
case KeyringPolicyWrite:
case KeyringPolicyDeny:
case "": // Special case to allow omitting the keyring policy
default:
return nil, fmt.Errorf("Invalid keyring policy: %#v", p.Keyring)
}
return p, nil
}
示例6: FromString
func FromString(filename string, contents string) (*Config, error) {
config := Config{}
err := hcl.Decode(&config, contents)
if err != nil {
return nil, err
}
config.SourceFilename = filename
return &config, nil
}
示例7: LoadTerraformConfig
func LoadTerraformConfig(path string) (*TerraformConfig, error) {
var value TerraformConfig
if _, err := os.Stat(path); err != nil {
return nil, err
}
err := hcl.Decode(&value, readFile(path))
if err != nil {
return nil, err
}
return &value, nil
}
示例8: Parse
// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
// Decode the rules
p := &Policy{}
if rules == "" {
// Hot path for empty rules
return p, nil
}
if err := hcl.Decode(p, rules); err != nil {
return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
}
// Validate the key policy
for _, kp := range p.Keys {
if !isPolicyValid(kp.Policy) {
return nil, fmt.Errorf("Invalid key policy: %#v", kp)
}
}
// Validate the service policy
for _, sp := range p.Services {
if !isPolicyValid(sp.Policy) {
return nil, fmt.Errorf("Invalid service policy: %#v", sp)
}
}
// Validate the user event policies
for _, ep := range p.Events {
if !isPolicyValid(ep.Policy) {
return nil, fmt.Errorf("Invalid event policy: %#v", ep)
}
}
// Validate the prepared query policies
for _, pq := range p.PreparedQueries {
if !isPolicyValid(pq.Policy) {
return nil, fmt.Errorf("Invalid query policy: %#v", pq)
}
}
// Validate the keyring policy - this one is allowed to be empty
if p.Keyring != "" && !isPolicyValid(p.Keyring) {
return nil, fmt.Errorf("Invalid keyring policy: %#v", p.Keyring)
}
// Validate the operator policy - this one is allowed to be empty
if p.Operator != "" && !isPolicyValid(p.Operator) {
return nil, fmt.Errorf("Invalid operator policy: %#v", p.Operator)
}
return p, nil
}
示例9: LoadConfigFile
func LoadConfigFile(configFile string) Config {
var conf Config
configData, err := ioutil.ReadFile(configFile)
if err != nil {
log.Fatalf("Error: Couldn't read config file %s: %s", configFile, err)
}
err = hcl.Decode(&conf, string(configData))
if err != nil {
log.Fatalf("Error parsing config file %s: %s", configFile, err)
}
return conf
}
示例10: InitializeConfig
func InitializeConfig() *Config {
var cfg Config
cfgData, err := ioutil.ReadFile(CfgFile)
if err != nil {
log.Fatalln("Unable to locate Config File. make sure you specify it using the --config flag")
return nil
}
err = hcl.Decode(&cfg, string(cfgData))
if err != nil {
log.Fatalln("Unable to parse Config File.")
return nil
}
return &cfg
}
示例11: parseVariableAsHCL
// parseVariableAsHCL 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 parseVariableAsHCL(name string, input string, targetType config.VariableType) (interface{}, error) {
// expecting a string so don't decode anything, just strip quotes
if targetType == config.VariableTypeString {
return strings.Trim(input, `"`), nil
}
// return empty types
if strings.TrimSpace(input) == "" {
switch targetType {
case config.VariableTypeList:
return []interface{}{}, nil
case config.VariableTypeMap:
return make(map[string]interface{}), nil
}
}
const sentinelValue = "SENTINEL_TERRAFORM_VAR_OVERRIDE_KEY"
inputWithSentinal := fmt.Sprintf("%s = %s", sentinelValue, input)
var decoded map[string]interface{}
err := hcl.Decode(&decoded, inputWithSentinal)
if err != nil {
return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL: %s", name, input, err)
}
if len(decoded) != 1 {
return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. Only one value may be specified.", name, input)
}
parsedValue, ok := decoded[sentinelValue]
if !ok {
return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.", name, input)
}
switch targetType {
case config.VariableTypeList:
return parsedValue, nil
case config.VariableTypeMap:
if list, ok := parsedValue.([]map[string]interface{}); ok {
return list[0], nil
}
return nil, fmt.Errorf("Cannot parse value for variable %s (%q) as valid HCL. One value must be specified.", name, input)
default:
panic(fmt.Errorf("unknown type %s", targetType.Printable()))
}
}
示例12: Parse
// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
// Decode the rules
p := &Policy{Raw: rules}
if err := hcl.Decode(p, rules); err != nil {
return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
}
// Validate the path policy
for _, pc := range p.Paths {
// Strip the glob character if found
if strings.HasSuffix(pc.Prefix, "*") {
pc.Prefix = strings.TrimSuffix(pc.Prefix, "*")
pc.Glob = true
}
// Map old-style policies into capabilities
switch pc.Policy {
case OldDenyPathPolicy:
pc.Capabilities = []string{DenyCapability}
case OldReadPathPolicy:
pc.Capabilities = append(pc.Capabilities, []string{ReadCapability, ListCapability}...)
case OldWritePathPolicy:
pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability}...)
case OldSudoPathPolicy:
pc.Capabilities = append(pc.Capabilities, []string{CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability}...)
}
// Initialize the map
pc.CapabilitiesBitmap = 0
for _, cap := range pc.Capabilities {
switch cap {
// If it's deny, don't include any other capability
case DenyCapability:
pc.Capabilities = []string{DenyCapability}
pc.CapabilitiesBitmap = DenyCapabilityInt
goto PathFinished
case CreateCapability, ReadCapability, UpdateCapability, DeleteCapability, ListCapability, SudoCapability:
pc.CapabilitiesBitmap |= cap2Int[cap]
default:
return nil, fmt.Errorf("Invalid capability: %#v", pc)
}
}
PathFinished:
}
return p, nil
}
示例13: applyConfigFile
func applyConfigFile(options *Options, filePath string) error {
filePath = ExpandHomeDir(filePath)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return err
}
fileString := []byte{}
log.Printf("Loading config file at: %s", filePath)
fileString, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
config := make(map[string]interface{})
hcl.Decode(&config, string(fileString))
o := structs.New(options)
for _, name := range o.Names() {
configName := strings.ToLower(strings.Join(camelcase.Split(name), "_"))
if val, ok := config[configName]; ok {
field, ok := o.FieldOk(name)
if !ok {
return errors.New("No such option: " + name)
}
var err error
if name == "Preferences" {
prefs := val.([]map[string]interface{})[0]
htermPrefs := make(map[string]interface{})
for key, value := range prefs {
htermPrefs[strings.Replace(key, "_", "-", -1)] = value
}
err = field.Set(htermPrefs)
} else {
err = field.Set(val)
}
if err != nil {
return err
}
}
}
return nil
}
示例14: initConfig
func initConfig() Config {
var configPath = os.Getenv("HOME")
var c Config
var err error
config, err := ioutil.ReadFile(filepath.Join(configPath, configFile))
if err != nil {
log.Printf("Error parsing config: %s", err)
configUsage()
}
err = hcl.Decode(&c, string(config))
if err != nil {
log.Fatalf("Configuration decode error: %s", err)
}
return c
}
示例15: readConfig
func readConfig() *Config {
bts, err := ioutil.ReadFile(Path())
if err != nil {
printer.SayErr("Could not read %s", Path())
os.Exit(1)
}
var cfg *Config
defaults := DefaultConfig()
err = hcl.Decode(&cfg, string(bts[:]))
if err != nil {
printer.SayErr("[dcdr] config parse error %+v", err)
os.Exit(1)
}
if cfg.Namespace == "" {
cfg.Namespace = defaults.Namespace
}
if cfg.Username == "" {
cfg.Username = defaults.Username
}
if cfg.Watcher.OutputPath == "" {
cfg.Watcher.OutputPath = defaults.Watcher.OutputPath
}
if cfg.Server.Host == "" {
cfg.Server.Host = defaults.Server.Host
}
if cfg.Server.Endpoint == "" {
cfg.Server.Endpoint = defaults.Server.Endpoint
}
if cfg.Server.JSONRoot == "" {
cfg.Server.JSONRoot = defaults.Server.JSONRoot
}
return cfg
}