// inferTypeFromDefault contains the logic for the old method of inferring // variable types - we can also use this for validating that the declared // type matches the type of the default value func (v *Variable) inferTypeFromDefault() VariableType { if v.Default == nil { return VariableTypeString } var s string if err := mapstructure.WeakDecode(v.Default, &s); err == nil { v.Default = s return VariableTypeString } var m map[string]string if err := mapstructure.WeakDecode(v.Default, &m); err == nil { v.Default = m return VariableTypeMap } var l []string if err := mapstructure.WeakDecode(v.Default, &l); err == nil { v.Default = l return VariableTypeList } return VariableTypeUnknown }
func parseResources(result *structs.Resources, list *ast.ObjectList) error { list = list.Elem() if len(list.Items) == 0 { return nil } if len(list.Items) > 1 { return fmt.Errorf("only one 'resource' block allowed per task") } // Get our resource object o := list.Items[0] // We need this later var listVal *ast.ObjectList if ot, ok := o.Val.(*ast.ObjectType); ok { listVal = ot.List } else { return fmt.Errorf("resource: should be an object") } var m map[string]interface{} if err := hcl.DecodeObject(&m, o.Val); err != nil { return err } delete(m, "network") if err := mapstructure.WeakDecode(m, result); err != nil { return err } // Parse the network resources if o := listVal.Filter("network"); len(o.Items) > 0 { if len(o.Items) > 1 { return fmt.Errorf("only one 'network' resource allowed") } var r structs.NetworkResource var m map[string]interface{} if err := hcl.DecodeObject(&m, o.Items[0].Val); err != nil { return err } if err := mapstructure.WeakDecode(m, &r); err != nil { return err } var networkObj *ast.ObjectList if ot, ok := o.Items[0].Val.(*ast.ObjectType); ok { networkObj = ot.List } else { return fmt.Errorf("resource: should be an object") } if err := parsePorts(networkObj, &r); err != nil { return err } result.Networks = []*structs.NetworkResource{&r} } return nil }
func (m schemaMap) diffString( k string, schema *Schema, diff *terraform.InstanceDiff, d *ResourceData, all bool) error { var originalN interface{} var os, ns string o, n, _, _ := d.diffChange(k) if n == nil { n = schema.Default if schema.DefaultFunc != nil { var err error n, err = schema.DefaultFunc() if err != nil { return fmt.Errorf("%s, error loading default: %s", k, err) } } } if schema.StateFunc != nil { originalN = n n = schema.StateFunc(n) } if err := mapstructure.WeakDecode(o, &os); err != nil { return fmt.Errorf("%s: %s", k, err) } if err := mapstructure.WeakDecode(n, &ns); err != nil { return fmt.Errorf("%s: %s", k, err) } if os == ns && !all { // They're the same value. If there old value is not blank or we // have an ID, then return right away since we're already setup. if os != "" || d.Id() != "" { return nil } // Otherwise, only continue if we're computed if !schema.Computed { return nil } } removed := false if o != nil && n == nil { removed = true } if removed && schema.Computed { return nil } diff.Attributes[k] = schema.finalizeDiff(&terraform.ResourceAttrDiff{ Old: os, New: ns, NewExtra: originalN, NewRemoved: removed, }) return nil }
func parseResources(result *structs.Resources, obj *hclobj.Object) error { if obj.Len() > 1 { return fmt.Errorf("only one 'resource' block allowed per task") } for _, o := range obj.Elem(false) { var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } delete(m, "network") if err := mapstructure.WeakDecode(m, result); err != nil { return err } // Parse the network resources if o := o.Get("network", false); o != nil { if o.Len() > 1 { return fmt.Errorf("only one 'network' resource allowed") } var r structs.NetworkResource var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } if err := mapstructure.WeakDecode(m, &r); err != nil { return err } // Keep track of labels we've already seen so we can ensure there // are no collisions when we turn them into environment variables. // lowercase:NomalCase so we can get the first for the error message seenLabel := map[string]string{} for _, label := range r.DynamicPorts { if !reDynamicPorts.MatchString(label) { return errDynamicPorts } first, seen := seenLabel[strings.ToLower(label)] if seen { return fmt.Errorf("Found a port label collision: `%s` overlaps with previous `%s`", label, first) } else { seenLabel[strings.ToLower(label)] = label } } result.Networks = []*structs.NetworkResource{&r} } } return nil }
func (m schemaMap) validatePrimitive( k string, raw interface{}, schema *Schema, c *terraform.ResourceConfig) ([]string, []error) { if c.IsComputed(k) { // If the key is being computed, then it is not an error return nil, nil } var decoded interface{} switch schema.Type { case TypeBool: // Verify that we can parse this as the correct type var n bool if err := mapstructure.WeakDecode(raw, &n); err != nil { return nil, []error{err} } decoded = n case TypeInt: // Verify that we can parse this as an int var n int if err := mapstructure.WeakDecode(raw, &n); err != nil { return nil, []error{err} } decoded = n case TypeFloat: // Verify that we can parse this as an int var n float64 if err := mapstructure.WeakDecode(raw, &n); err != nil { return nil, []error{err} } decoded = n case TypeString: // Verify that we can parse this as a string var n string if err := mapstructure.WeakDecode(raw, &n); err != nil { return nil, []error{err} } decoded = n default: panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type)) } if schema.ValidateFunc != nil { return schema.ValidateFunc(decoded, k) } return nil, nil }
func (self *Zusaar) Get(baseurl, keyword, nickname string, places []string) ([]Event, error) { var events []Event for _, param := range []string{"keyword_or=" + url.QueryEscape(keyword), "owner_nickname=" + nickname, "nickname=" + nickname} { for t := time.Now().Local(); t.Before(time.Now().Local().AddDate(0, 3, 0)); t = t.AddDate(0, 1, 0) { query := param + "&ym=" + t.Format("200601") result, err := GetJson(baseurl + query) if err != nil { return nil, err } if err = mapstructure.WeakDecode(result, &self.result); err != nil { return nil, err } for _, e := range self.result.Event { event := Event{ Id: e.Event_id, Title: e.Title, Started_at: format(e.Started_at), Url: e.Event_url, Summary: e.Catch, Place: e.Address + "\n" + e.Place, Description: parse(e.Description), } if event.Summary == "" { event.Summary = trim(event.Description) } events = append(events, event) } time.Sleep(time.Duration(1 * time.Second)) } } return events, nil }
func parseProject(result *File, obj *hclobj.Object) error { if obj.Len() > 1 { return fmt.Errorf("only one 'project' block allowed") } // Check for invalid keys valid := []string{"name", "infrastructure"} if err := checkHCLKeys(obj, valid); err != nil { return multierror.Prefix(err, "project:") } var m map[string]interface{} if err := hcl.DecodeObject(&m, obj); err != nil { return err } // Parse the project var proj Project result.Project = &proj if err := mapstructure.WeakDecode(m, &proj); err != nil { return err } return nil }
func parseDetect(result *Config, obj *hclobj.Object) error { // 从map中获取所有实际对象的key值 objects := make([]*hclobj.Object, 0, 2) for _, o1 := range obj.Elem(false) { for _, o2 := range o1.Elem(true) { objects = append(objects, o2) } } if len(objects) == 0 { return nil } // 检查每个对象,返回实际结果 collection := make([]*Detector, 0, len(objects)) for _, o := range objects { var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } var d Detector if err := mapstructure.WeakDecode(m, &d); err != nil { return fmt.Errorf("解析detector错误 '%s' : %s", o.Key, err) } d.Type = o.Key collection = append(collection, &d) } result.Detectors = collection return nil }
func (r *DiffFieldReader) readPrimitive( address []string, schema *Schema) (FieldReadResult, error) { result, err := r.Source.ReadField(address) if err != nil { return FieldReadResult{}, err } attrD, ok := r.Diff.Attributes[strings.Join(address, ".")] if !ok { return result, nil } var resultVal string if !attrD.NewComputed { resultVal = attrD.New if attrD.NewExtra != nil { result.ValueProcessed = resultVal if err := mapstructure.WeakDecode(attrD.NewExtra, &resultVal); err != nil { return FieldReadResult{}, err } } } result.Computed = attrD.NewComputed result.Exists = true result.Value, err = stringToPrimitive(resultVal, false, schema) if err != nil { return FieldReadResult{}, err } return result, nil }
func parseDetect(result *Config, obj *hclobj.Object) error { // Get all the maps of keys to the actual object objects := make([]*hclobj.Object, 0, 2) for _, o1 := range obj.Elem(false) { for _, o2 := range o1.Elem(true) { objects = append(objects, o2) } } if len(objects) == 0 { return nil } // Go through each object and turn it into an actual result. collection := make([]*Detector, 0, len(objects)) for _, o := range objects { var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } var d Detector if err := mapstructure.WeakDecode(m, &d); err != nil { return fmt.Errorf( "error parsing detector '%s': %s", o.Key, err) } d.Type = o.Key collection = append(collection, &d) } result.Detectors = collection return nil }
func parseAtlas(result **AtlasConfig, list *ast.ObjectList) error { list = list.Elem() if len(list.Items) > 1 { return fmt.Errorf("only one 'atlas' block allowed") } // Get our atlas object listVal := list.Items[0].Val // Check for invalid keys valid := []string{ "infrastructure", "token", "join", "endpoint", } if err := checkHCLKeys(listVal, valid); err != nil { return err } var m map[string]interface{} if err := hcl.DecodeObject(&m, listVal); err != nil { return err } var atlas AtlasConfig if err := mapstructure.WeakDecode(m, &atlas); err != nil { return err } *result = &atlas return nil }
func parseTLSConfig(result **config.TLSConfig, list *ast.ObjectList) error { list = list.Elem() if len(list.Items) > 1 { return fmt.Errorf("only one 'tls' block allowed") } // Get the TLS object listVal := list.Items[0].Val valid := []string{ "http", "rpc", "verify_server_hostname", "ca_file", "cert_file", "key_file", } if err := checkHCLKeys(listVal, valid); err != nil { return err } var m map[string]interface{} if err := hcl.DecodeObject(&m, listVal); err != nil { return err } var tlsConfig config.TLSConfig if err := mapstructure.WeakDecode(m, &tlsConfig); err != nil { return err } *result = &tlsConfig return nil }
func parseLocalDisk(result **structs.LocalDisk, list *ast.ObjectList) error { list = list.Elem() if len(list.Items) > 1 { return fmt.Errorf("only one 'local_disk' block allowed") } // Get our local_disk object obj := list.Items[0] // Check for invalid keys valid := []string{ "sticky", "disk", } if err := checkHCLKeys(obj.Val, valid); err != nil { return err } var m map[string]interface{} if err := hcl.DecodeObject(&m, obj.Val); err != nil { return err } var localDisk structs.LocalDisk if err := mapstructure.WeakDecode(m, &localDisk); err != nil { return err } *result = &localDisk return nil }
func parseUpdate(result *structs.UpdateStrategy, obj *hclobj.Object) error { if obj.Len() > 1 { return fmt.Errorf("only one 'update' block allowed per job") } for _, o := range obj.Elem(false) { var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } for _, key := range []string{"stagger", "Stagger"} { if raw, ok := m[key]; ok { switch v := raw.(type) { case string: dur, err := time.ParseDuration(v) if err != nil { return fmt.Errorf("invalid stagger time '%s'", raw) } m[key] = dur case int: m[key] = time.Duration(v) * time.Second default: return fmt.Errorf("invalid type for stagger time '%s'", raw) } } } if err := mapstructure.WeakDecode(m, result); err != nil { return err } } return nil }
func (c *AuditEnableCommand) Run(args []string) int { var desc, id string flags := c.Meta.FlagSet("audit-enable", FlagSetDefault) flags.StringVar(&desc, "description", "", "") flags.StringVar(&id, "id", "", "") flags.Usage = func() { c.Ui.Error(c.Help()) } if err := flags.Parse(args); err != nil { return 1 } args = flags.Args() if len(args) < 1 { flags.Usage() c.Ui.Error(fmt.Sprintf( "\naudit-enable expects at least one argument: the type to enable")) return 1 } auditType := args[0] if id == "" { id = auditType } // Build the options var stdin io.Reader = os.Stdin if c.testStdin != nil { stdin = c.testStdin } builder := &kvbuilder.Builder{Stdin: stdin} if err := builder.Add(args[1:]...); err != nil { c.Ui.Error(fmt.Sprintf( "Error parsing options: %s", err)) return 1 } var opts map[string]string if err := mapstructure.WeakDecode(builder.Map(), &opts); err != nil { c.Ui.Error(fmt.Sprintf( "Error parsing options: %s", err)) return 1 } client, err := c.Client() if err != nil { c.Ui.Error(fmt.Sprintf( "Error initializing client: %s", err)) return 1 } err = client.Sys().EnableAudit(id, auditType, desc, opts) if err != nil { c.Ui.Error(fmt.Sprintf( "Error enabling audit backend: %s", err)) return 1 } c.Ui.Output(fmt.Sprintf( "Successfully enabled audit backend '%s'!", auditType)) return 0 }
func parseUpdate(result *structs.UpdateStrategy, obj *hclobj.Object) error { if obj.Len() > 1 { return fmt.Errorf("only one 'update' block allowed per job") } for _, o := range obj.Elem(false) { var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } for _, key := range []string{"stagger", "Stagger"} { if raw, ok := m[key]; ok { staggerTime, err := toDuration(raw) if err != nil { return fmt.Errorf("Invalid stagger time: %v", err) } m[key] = staggerTime } } if err := mapstructure.WeakDecode(m, result); err != nil { return err } } return nil }
func (self *Eventbrite) Get(baseurl, keyword, nickname string) ([]Event, error) { var events []Event for _, param := range strings.Split(keyword, ",") { query := "q=" + param result, err := GetJson(baseurl + query) if err != nil { return nil, err } if err = mapstructure.WeakDecode(result, &self.result); err != nil { return nil, err } for _, e := range self.result.Events { event := Event{ Id: e.Id, Title: e.Name.Text, Started_at: format(e.Start.Utc), Url: e.Url, Summary: trim(e.Description.Text), Place: e.Venue.Address.Address_1 + "\n" + e.Venue.Address.City, Description: e.Description.Text, } events = append(events, event) } time.Sleep(time.Duration(1 * time.Second)) } return events, nil }
// New creates a new App with the provided environment. func New(env map[string]string) (*App, error) { var app App appVar := env["VCAP_APPLICATION"] if err := json.Unmarshal([]byte(appVar), &app); err != nil { return nil, err } app.Home = env["HOME"] app.MemoryLimit = env["MEMORY_LIMIT"] app.WorkingDir = env["PWD"] app.TempDir = env["TMPDIR"] app.User = env["USER"] var rawServices map[string]interface{} servicesVar := env["VCAP_SERVICES"] if err := json.Unmarshal([]byte(servicesVar), &rawServices); err != nil { return nil, err } services := make(map[string][]Service) for k, v := range rawServices { var serviceInstances []Service if err := mapstructure.WeakDecode(v, &serviceInstances); err != nil { return nil, err } services[k] = serviceInstances } app.Services = services return &app, nil }
func parseConstraints(result *[]*structs.Constraint, obj *hclobj.Object) error { for _, o := range obj.Elem(false) { var m map[string]interface{} if err := hcl.DecodeObject(&m, o); err != nil { return err } m["LTarget"] = m["attribute"] m["RTarget"] = m["value"] m["Operand"] = m["operator"] // Default constraint to being hard if _, ok := m["hard"]; !ok { m["hard"] = true } // Build the constraint var c structs.Constraint if err := mapstructure.WeakDecode(m, &c); err != nil { return err } if c.Operand == "" { c.Operand = "=" } *result = append(*result, &c) } return nil }
func parseAdvertise(result **AdvertiseAddrs, list *ast.ObjectList) error { list = list.Elem() if len(list.Items) > 1 { return fmt.Errorf("only one 'advertise' block allowed") } // Get our advertise object listVal := list.Items[0].Val // Check for invalid keys valid := []string{ "http", "rpc", "serf", } if err := checkHCLKeys(listVal, valid); err != nil { return err } var m map[string]interface{} if err := hcl.DecodeObject(&m, listVal); err != nil { return err } var advertise AdvertiseAddrs if err := mapstructure.WeakDecode(m, &advertise); err != nil { return err } *result = &advertise return nil }
func parsePorts(networkObj *ast.ObjectList, nw *structs.NetworkResource) error { portsObjList := networkObj.Filter("port") knownPortLabels := make(map[string]bool) for _, port := range portsObjList.Items { if len(port.Keys) == 0 { return fmt.Errorf("ports must be named") } label := port.Keys[0].Token.Value().(string) if !reDynamicPorts.MatchString(label) { return errPortLabel } l := strings.ToLower(label) if knownPortLabels[l] { return fmt.Errorf("found a port label collision: %s", label) } var p map[string]interface{} var res structs.Port if err := hcl.DecodeObject(&p, port.Val); err != nil { return err } if err := mapstructure.WeakDecode(p, &res); err != nil { return err } res.Label = label if res.Value > 0 { nw.ReservedPorts = append(nw.ReservedPorts, res) } else { nw.DynamicPorts = append(nw.DynamicPorts, res) } knownPortLabels[l] = true } return nil }
func parseDetect(result *Config, list *ast.ObjectList) error { if len(list.Items) == 0 { return nil } // Go through each object and turn it into an actual result. collection := make([]*Detector, 0, len(list.Items)) for _, item := range list.Items { key := item.Keys[0].Token.Value().(string) var m map[string]interface{} if err := hcl.DecodeObject(&m, item.Val); err != nil { return err } var d Detector if err := mapstructure.WeakDecode(m, &d); err != nil { return fmt.Errorf( "error parsing detector '%s': %s", key, err) } d.Type = key collection = append(collection, &d) } result.Detectors = collection return nil }
func (r *ConfigFieldReader) readPrimitive( k string, schema *Schema) (FieldReadResult, error) { raw, ok := r.Config.Get(k) if !ok { // Nothing in config, but we might still have a default from the schema var err error raw, err = schema.DefaultValue() if err != nil { return FieldReadResult{}, fmt.Errorf("%s, error loading default: %s", k, err) } if raw == nil { return FieldReadResult{}, nil } } var result string if err := mapstructure.WeakDecode(raw, &result); err != nil { return FieldReadResult{}, err } computed := r.Config.IsComputed(k) returnVal, err := stringToPrimitive(result, computed, schema) if err != nil { return FieldReadResult{}, err } return FieldReadResult{ Value: returnVal, Exists: true, Computed: computed, }, nil }
func parseProject(result *File, list *ast.ObjectList) error { if len(list.Items) > 1 { return fmt.Errorf("only one 'project' block allowed") } // Get our one item item := list.Items[0] // Check for invalid keys valid := []string{"name", "infrastructure"} if err := checkHCLKeys(item.Val, valid); err != nil { return multierror.Prefix(err, "project:") } var m map[string]interface{} if err := hcl.DecodeObject(&m, item.Val); err != nil { return err } // Parse the project var proj Project result.Project = &proj if err := mapstructure.WeakDecode(m, &proj); err != nil { return err } return nil }
func (self *Strtacademy) Get(baseurl, keyword, nickname string, places []string) ([]Event, error) { var events []Event for i := 1; i <= 10; i++ { result, err := GetJson(baseurl + strconv.Itoa(i)) if err != nil { return nil, err } if err = mapstructure.WeakDecode(result, &self.result); err != nil { return nil, err } for _, strtacademy := range self.result.Events { event := Event{ Id: strtacademy.Event_id, Title: strtacademy.Title, Started_at: format(strtacademy.Start_at), Url: strtacademy.Url, Summary: trim(strtacademy.Details), Place: strtacademy.Address + "\n" + strtacademy.Venue, Description: strtacademy.Details, } if !event.contains(keyword) { continue } events = append(events, event) } time.Sleep(time.Duration(1 * time.Second)) } return events, nil }
func (self *Meetup) Get(baseurl, keyword, nickname string, places []string) ([]Event, error) { var events []Event for _, param := range strings.Split(keyword, ",") { query := "topic=" + param result, err := GetJson(baseurl + query) if err != nil { return nil, err } if err = mapstructure.WeakDecode(result, &self.result); err != nil { return nil, err } for _, e := range self.result.Results { event := Event{ Id: e.Id, Title: e.Name, Started_at: formatEpoch(e.Time), Url: e.Event_url, Place: e.Venue.Address_1 + "\n" + e.Venue.City, Description: parse(e.Description), } event.Summary = trim(event.Description) events = append(events, event) } time.Sleep(time.Duration(1 * time.Second)) } return events, nil }
func parseTelemetry(result **Telemetry, list *ast.ObjectList) error { list = list.Elem() if len(list.Items) > 1 { return fmt.Errorf("only one 'telemetry' block allowed") } // Get our telemetry object listVal := list.Items[0].Val // Check for invalid keys valid := []string{ "statsite_address", "statsd_address", "disable_hostname", } if err := checkHCLKeys(listVal, valid); err != nil { return err } var m map[string]interface{} if err := hcl.DecodeObject(&m, listVal); err != nil { return err } var telemetry Telemetry if err := mapstructure.WeakDecode(m, &telemetry); err != nil { return err } *result = &telemetry return nil }
func (self *Partake) Get(baseurl, keyword, nickname string) ([]Event, error) { var events []Event for _, param := range strings.Split(keyword, ",") { result, err := GetJson(baseurl + url.QueryEscape(param)) if err != nil { return nil, err } if err = mapstructure.WeakDecode(result, &self.result); err != nil { return nil, err } for _, e := range self.result.Events { event := Event{ Id: e.Id, Title: e.Title, Started_at: e.BeginDate, Url: "http://partake.in/events/" + e.Id, Summary: e.Summary, Place: e.Address + "\n" + e.Place, Description: e.Description, } events = append(events, event) } time.Sleep(time.Duration(1 * time.Second)) } return events, nil }
// TODO: test func (n *EvalVariableBlock) Eval(ctx EvalContext) (interface{}, error) { // Clear out the existing mapping for k, _ := range n.Variables { delete(n.Variables, k) } // Get our configuration rc := *n.Config for k, v := range rc.Config { var vStr string if err := mapstructure.WeakDecode(v, &vStr); err != nil { return nil, errwrap.Wrapf(fmt.Sprintf( "%s: error reading value: {{err}}", k), err) } n.Variables[k] = vStr } for k, _ := range rc.Raw { if _, ok := n.Variables[k]; !ok { n.Variables[k] = config.UnknownVariableValue } } return nil, nil }
func (self *Doorkeeper) Get(baseurl, keyword, nickname string, places []string) ([]Event, error) { t := time.Now().Format("2006-01-02") param := "since=" + t result, err := GetJson(baseurl + param) if err != nil { return nil, err } if err = mapstructure.WeakDecode(result, &self.result); err != nil { return nil, err } var events []Event for _, e := range self.result { event := Event{ Id: e.Event.Id, Title: e.Event.Title, Started_at: format(e.Event.Starts_at), Url: e.Event.Public_url, Place: e.Event.Address + "\n" + e.Event.Venue_name, Description: parse(e.Event.Description), } event.Summary = trim(event.Description) if !event.contains(keyword) { continue } events = append(events, event) } return events, nil }