// Takes the current parser and return a new parser with // appropriate for use within a command function func (self *ArgParser) SubParser() *ArgParser { parser := NewParser() src := structs.New(self) dest := structs.New(parser) // Copy all the public values for _, field := range src.Fields() { if field.IsExported() { dest.Field(field.Name()).Set(field.Value()) } } parser.args = self.args parser.rules = self.rules parser.log = self.log parser.helpAdded = self.helpAdded parser.addHelp = self.addHelp parser.options = self.options parser.flags = self.flags // Remove all Commands from our rules for i := len(parser.rules) - 1; i >= 0; i-- { if parser.rules[i].HasFlag(IsCommand) { // Remove the rule parser.rules = append(parser.rules[:i], parser.rules[i+1:]...) } } // Clear the selected Commands parser.Command = nil parser.IsSubParser = true return parser }
func (b *backend) pathCRLRead( req *logical.Request, d *framework.FieldData) (*logical.Response, error) { name := strings.ToLower(d.Get("name").(string)) if name == "" { return logical.ErrorResponse(`"name" parameter must be set`), nil } b.crlUpdateMutex.RLock() defer b.crlUpdateMutex.RUnlock() var retData map[string]interface{} crl, ok := b.crls[name] if !ok { return logical.ErrorResponse(fmt.Sprintf( "no such CRL %s", name, )), nil } retData = structs.New(&crl).Map() return &logical.Response{ Data: retData, }, nil }
// Load loads the source into the config defined by struct s func (f *FlagLoader) Load(s interface{}) error { if f.FlagTagName == "" { f.FlagTagName = "flag" } strct := structs.New(s) structName := strct.Name() flagSet := flag.NewFlagSet(structName, flag.ExitOnError) for _, field := range strct.Fields() { f.processField(flagSet, field.Name(), field) } //flagSet.Usage no use for now, we still use other library for full command //line argument parsing. //flagSet.Usage = func() { //fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) //flagSet.PrintDefaults() //fmt.Fprintf(os.Stderr, "\nGenerated environment variables:\n") //e := &EnvironmentLoader{ // Prefix: f.EnvPrefix, // CamelCase: f.CamelCase, //} //e.PrintEnvs(s) //fmt.Println("") //} args := os.Args[1:] if f.Args != nil { args = f.Args } return flagSet.Parse(args) }
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 }
// pathRoleRead is used to view the information registered for a given AMI ID. func (b *backend) pathRoleRead( req *logical.Request, data *framework.FieldData) (*logical.Response, error) { roleEntry, err := b.lockedAWSRole(req.Storage, strings.ToLower(data.Get("role").(string))) if err != nil { return nil, err } if roleEntry == nil { return nil, nil } // Prepare the map of all the entries in the roleEntry. respData := structs.New(roleEntry).Map() // HMAC key belonging to the role should NOT be exported. delete(respData, "hmac_key") // Display the ttl in seconds. respData["ttl"] = roleEntry.TTL / time.Second // Display the max_ttl in seconds. respData["max_ttl"] = roleEntry.MaxTTL / time.Second return &logical.Response{ Data: respData, }, nil }
func initialize() { // remove temp files os.RemoveAll(DBdir) // open db d, err := db.OpenDB(DBdir) if err != nil { panic(err) } // create collection if err := d.Create("Entries"); err != nil { panic(err) } // collection instance docEntries := d.Use("Entries") // dummy data entries := Entries{ &Entry{1, time.Now(), "Entry 1", "First Entry!"}, &Entry{2, time.Now(), "Golang", "Go language is awesome"}, } // insert each for _, entry := range entries { docEntries.Insert(structs.New(entry).Map()) } }
func FromRequest(req *restful.Request, raw interface{}) (bson.M, error) { result := bson.M{} s := structs.New(raw) fields: for _, field := range s.Fields() { name := field.Name() tags := strings.Split(field.Tag(FilterTag), ",") if len(tags) > 0 { name = tags[0] // take field name from tag tags = tags[1:] } bsonName := getBsonName(field) if bsonName == "" { bsonName = name } val := req.QueryParameter(name) if val != "" { if v, err := parseValue(field, val); err != nil { return nil, fmt.Errorf("param %s: %v", name, err) } else { result[bsonName] = v // if there is an eq value then we just skip modifiers continue fields } } modifiers := getModifiers(tags) modifiers: for _, m := range modifiers { mName := fmt.Sprintf("%s%s%s", name, ModifierDivider, m) val := req.QueryParameter(mName) if val == "" { continue modifiers } if m == in || m == nin { ins := []interface{}{} for _, val := range strings.Split(val, ",") { if val == "" { continue } if v, err := parseValue(field, val); err != nil { return nil, fmt.Errorf("param %s: %v", mName, err) } else { ins = append(ins, v) } } result[bsonName] = bson.M{fmt.Sprintf("$%s", m): ins} continue modifiers } // gt, gte, lt, lte, ne if v, err := parseValue(field, val); err != nil { return nil, fmt.Errorf("param %s: %v", name, err) } else { result[bsonName] = bson.M{fmt.Sprintf("$%s", m): v} // if there is an eq value then we just skip modifiers continue fields } } } return result, nil }
func (b *backend) pathRoleRead( req *logical.Request, data *framework.FieldData) (*logical.Response, error) { role, err := b.getRole(req.Storage, data.Get("name").(string)) if err != nil { return nil, err } if role == nil { return nil, nil } hasMax := true if len(role.MaxTTL) == 0 { role.MaxTTL = "(system default)" hasMax = false } if len(role.TTL) == 0 { if hasMax { role.TTL = "(system default, capped to role max)" } else { role.TTL = "(system default)" } } resp := &logical.Response{ Data: structs.New(role).Map(), } return resp, nil }
func GetQuery(raw interface{}) bson.M { result := bson.M{} if raw == nil { return result } s := structs.New(raw) for _, field := range s.Fields() { if field.IsZero() { continue } name := field.Name() if tagValue := field.Tag(FilterTag); tagValue != "" { tags := strings.Split(tagValue, ",") if len(tags) > 0 { if tags[0] != "" { name = tags[0] // take field name from tag } } } bsonName := getBsonName(field) if bsonName == "" { bsonName = name } result[bsonName] = field.Value() } return result }
// this is a confusing hack that I'm using because slack's RTM websocket // doesn't seem to support their own markup syntax. So anything that looks // like it has markup in it is sent into this function by the write thread // instead of into the websocket where it belongs. func apiPostMessage(e Event) { Logger.Debug(`Posting through api`) var req = ApiRequest{ URL: `https://slack.com/api/chat.postMessage`, Values: make(url.Values), Broker: e.Broker, } req.Values.Set(`channel`, e.Channel) req.Values.Set(`text`, e.Text) if e.Attachments != nil { aJson, _ := json.Marshal(e.Attachments) req.Values.Set(`attachments`, string(aJson)) } req.Values.Set(`id`, strconv.Itoa(int(e.ID))) req.Values.Set(`as_user`, e.Broker.Config.Name) req.Values.Set(`pretty`, `1`) authResp, _ := MakeAPIReq(req) s := structs.New(authResp) // convert this to a map[string]interface{} why not? hax. resp := s.Map() if replyVal, isReply := resp[`reply_to`]; isReply { if replyVal != nil { e.Broker.handleApiReply(resp) } } }
func (b *Builder) buildStruct(v interface{}, obj Object, ignored ...string) { for _, field := range structs.New(toStruct(v)).Fields() { if !field.IsExported() { continue } key := b.keyFromField(field) if key == "" { continue } if !b.Recursive { b.set(obj, key, field.Value(), ignored...) continue } if s, ok := field.Value().(fmt.Stringer); ok && b.FlatStringers { if !reflect.ValueOf(s).IsNil() { b.set(obj, key, s.String(), ignored...) } continue } child := flatten(field.Value()) if child == nil { b.set(obj, key, field.Value(), ignored...) continue } b.New(key).build(child, obj, ignored...) } }
func where(in interface{}, field string, sliceVal interface{}) ([]interface{}, error) { ret := make([]interface{}, 0) if in == nil { return ret, errors.New("where: source is nil") } if field == "" { return ret, errors.New("where: field is empty") } if sliceVal == nil { return ret, errors.New("where: value is nil") } if reflect.TypeOf(in).Kind() != reflect.Slice { return ret, errors.New("where: source is no slice value") } s := reflect.ValueOf(in) for i := 0; i < s.Len(); i++ { val := s.Index(i).Interface() st := structs.New(val) fieldVal, ok := st.FieldOk(field) if !ok { return ret, errors.Errorf("where: key %q not found", field) } if fieldVal.Value() == sliceVal { ret = append(ret, val) } } return ret, nil }
// Load loads the source into the config defined by struct s func (f *FlagLoader) Load(s interface{}) error { strct := structs.New(s) structName := strct.Name() flagSet := flag.NewFlagSet(structName, flag.ExitOnError) f.flagSet = flagSet for _, field := range strct.Fields() { f.processField(field.Name(), field) } flagSet.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) flagSet.PrintDefaults() fmt.Fprintf(os.Stderr, "\nGenerated environment variables:\n") e := &EnvironmentLoader{ Prefix: f.EnvPrefix, CamelCase: f.CamelCase, } e.PrintEnvs(s) fmt.Println("") } args := os.Args[1:] if f.Args != nil { args = f.Args } return flagSet.Parse(args) }
func printAppDetail(a App) { var output []string var outputEnv []string fields := structs.New(a).Fields() fmt.Println("\nApplication Details:") for _, f := range fields { if f.Name() == "Addresses" { output = append(output, fmt.Sprintf("%s:\n", f.Name())) for _, v := range a.Addresses { output = append(output, fmt.Sprintf("……|%s", v)) } } else if f.Name() == "Certificates" { output = append(output, fmt.Sprintf("%s:| Use \"--full\" to see certificates", f.Name())) output = append(output, fmt.Sprintf("– PrivateKey: |%s\n", a.Certificates["private_key"])) } else if f.Name() == "CreatedAt" { output = append(output, fmt.Sprintf("%s: | %s\n", f.Name(), utils.FormatTime(a.CreatedAt+"Z"))) } else if f.Name() == "CurrentDeployments" { output = append(output, fmt.Sprintf("%s:\n", f.Name())) for k, v := range a.CurrentDeployments { output = append(output, fmt.Sprintf("……|%s: %s", k, v)) } } else if f.Name() == "Environment" { outputEnv = append(outputEnv, fmt.Sprintf("%s:\n", f.Name())) for k, v := range a.Environment { outputEnv = append(outputEnv, fmt.Sprintf("%s=%s", k, v)) } } else if f.Name() == "Location" { output = append(output, fmt.Sprintf("%s: |Identifier: %s\t UUID: %s\n", f.Name(), a.Location["identifier"], a.Location["uuid"])) } else if f.Name() == "Metadata" { mdata, _ := json.Marshal(a.Metadata) output = append(output, fmt.Sprintf("%s: |%s\n", f.Name(), mdata)) } else if f.Name() == "Ports" { output = append(output, fmt.Sprintf("%s:\n", f.Name())) for _, v := range a.Ports { output = append(output, fmt.Sprintf("……|%s", v)) } } else if f.Name() == "Rules" { output = append(output, fmt.Sprintf("%s:\n", f.Name())) for k, v := range a.Rules { output = append(output, fmt.Sprintf("……|%s=%v", k, v)) } } else if f.Name() == "SSLPorts" { output = append(output, fmt.Sprintf("%s:\n", f.Name())) for _, v := range a.SSLPorts { output = append(output, fmt.Sprintf("……|%s", v)) } } else if f.Name() == "UpdatedAt" { output = append(output, fmt.Sprintf("%s: | %s\n", f.Name(), utils.FormatTime(a.UpdatedAt+"Z"))) } else { output = append(output, fmt.Sprintf("%s: |%v\n", f.Name(), f.Value())) } } fmt.Println(columnize.SimpleFormat(output)) fmt.Println("\n") fmt.Println(columnize.SimpleFormat(outputEnv)) }
func readErrorFromData(data interface{}) error { st := structs.New(data) if st.IsZero() { return nil } msgErr := st.Field("Error") return msgErr.Value().(error) }
func InitializeTask(runner *Runner) error { s := structs.New(*runner) for _, _ = range s.Fields() { // apply defaults here // log.Println(f, f.Tag("default")) } return nil }
// PrintEnvs prints the generated environment variables to the std out. func (e *EnvironmentLoader) PrintEnvs(s interface{}) { strct := structs.New(s) prefix := e.getPrefix(strct) for _, field := range strct.Fields() { e.printField(prefix, field) } }
func GetParams(ws *restful.WebService, raw interface{}) []*restful.Parameter { params := []*restful.Parameter{} s := structs.New(raw) for _, field := range s.Fields() { name := field.Name() tags := strings.Split(field.Tag(FilterTag), ",") if len(tags) > 0 { if tags[0] != "" { name = tags[0] // take field name from tag } tags = tags[1:] } modifiers := getModifiers(tags) desc := field.Tag("description") // generate description automatically if desc == "" { desc = fmt.Sprintf("filter by %s", name) if enum, casted := field.Value().(Enumer); casted { enumValues := enum.Enum() desc = fmt.Sprintf("%s, one of %v", desc, enumValues) } } if desc == "-" { desc = "" } dataType := "string" switch field.Kind() { case reflect.Int: dataType = "integer" case reflect.Float64: dataType = "number" case reflect.Float32: dataType = "number" case reflect.Bool: dataType = "boolean" } param := ws.QueryParameter(name, desc) if hasTag(tags, "required") { param.Required(true) } params = append(params, param) for _, m := range modifiers { mName := fmt.Sprintf("%s%s%s", name, ModifierDivider, m) param := ws.QueryParameter(mName, desc).DataType(dataType) if m == in || m == nin { param.AllowMultiple(true) } params = append(params, param) } } return params }
// ChangedFields returns the names of the changed fields since the last call to StartUpdate func (d Device) ChangedFields() (changed []string) { new := structs.New(d) fields := new.Names() if d.old == nil { return fields } old := structs.New(*d.old) for _, field := range new.Fields() { if !field.IsExported() || field.Name() == "old" { continue } if !reflect.DeepEqual(field.Value(), old.Field(field.Name()).Value()) { changed = append(changed, field.Name()) } } return }
func TestCertBundleParsing(t *testing.T) { cbuts := []*CertBundle{ refreshRSACertBundle(), refreshRSACertBundleWithChain(), refreshRSA8CertBundle(), refreshRSA8CertBundleWithChain(), refreshECCertBundle(), refreshECCertBundleWithChain(), refreshEC8CertBundle(), refreshEC8CertBundleWithChain(), } for i, cbut := range cbuts { jsonString, err := json.Marshal(cbut) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf("Error marshaling testing certbundle to JSON: %s", err) } pcbut, err := ParsePKIJSON(jsonString) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf("Error during JSON bundle handling: %s", err) } err = compareCertBundleToParsedCertBundle(cbut, pcbut) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf(err.Error()) } secret := &api.Secret{ Data: structs.New(cbut).Map(), } pcbut, err = ParsePKIMap(secret.Data) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf("Error during JSON bundle handling: %s", err) } err = compareCertBundleToParsedCertBundle(cbut, pcbut) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf(err.Error()) } pcbut, err = ParsePEMBundle(cbut.ToPEMBundle()) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf("Error during JSON bundle handling: %s", err) } err = compareCertBundleToParsedCertBundle(cbut, pcbut) if err != nil { t.Logf("Error occurred with bundle %d in test array (index %d).\n", i+1, i) t.Fatalf(err.Error()) } } }
func validateImmutibleFields(new, old interface{}, fldPath *field.Path, fields []string) field.ErrorList { allErrs := field.ErrorList{} olds := structs.New(old) news := structs.New(new) for _, f := range fields { // ommitting immutable fields is OK if news.Field(f).IsZero() { continue } if !reflect.DeepEqual(news.Field(f).Value(), olds.Field(f).Value()) { allErrs = append(allErrs, field.Forbidden(fldPath.Child(f), fmt.Sprintf("%s updates must not change %s", fldPath.String(), news.Field(f).Name()))) } } return allErrs }
func Update(db *sql.DB, entity IEntity) (sql.Result, error) { structInfo := structs.New(entity) fieldNames := structs.Names(entity) whereClause := "" var idValue interface{} setValueClause := "" values := make([]interface{}, 0) i := 0 for _, fieldName := range fieldNames { field := structInfo.Field(fieldName) if field.IsExported() { // 公有变量作为数据库字段 isPk := false tags := strings.Split(strings.Trim(field.Tag("db"), " "), ",") if len(tags) == 2 && tags[1] == "pk" { isPk = true } tag := tags[0] if isPk { // 更新时,只认主键作为更新条件 whereClause = fmt.Sprintf("WHERE %s = ?", tag) idValue = field.Value() } else { if !field.IsZero() { // 零值字段不更新 if i == 0 { setValueClause += fmt.Sprintf(" %s=? ", tag) } else { setValueClause += fmt.Sprintf(", %s=? ", tag) } values = append(values, field.Value()) i++ } } } } // 检查主键值 if idValue == nil || idValue == 0 { return nil, fmt.Errorf("the value of pk must be set") } values = append(values, idValue) updateSql := fmt.Sprintf("UPDATE %s SET %s %s", entity.TableName(), setValueClause, whereClause) stmt, err := db.Prepare(updateSql) if err != nil { return nil, err } res, err := stmt.Exec(values...) if err != nil { return nil, err } return res, nil }
func getRancherConfigObjects() map[string]bool { rancherConfig := structs.New(RancherConfig{}) fields := map[string]bool{} for _, field := range rancherConfig.Fields() { kind := field.Kind().String() if kind == "struct" || kind == "ptr" || kind == "slice" { split := strings.Split(field.Tag("yaml"), ",") fields[split[0]] = true } } return fields }
func (c *RekeyCommand) rekeyRetrieveStored(client *api.Client) int { storedKeys, err := client.Sys().RekeyRetrieveStored() if err != nil { c.Ui.Error(fmt.Sprintf("Error retrieving stored keys: %s", err)) return 1 } secret := &api.Secret{ Data: structs.New(storedKeys).Map(), } return OutputSecret(c.Ui, "table", secret) }
// Load loads the source into the config defined by struct s func (e *EnvironmentLoader) Load(s interface{}) error { strct := structs.New(s) prefix := e.getPrefix(strct) for _, field := range strct.Fields() { if err := e.processField(prefix, field); err != nil { return err } } return nil }
func (b *backend) pathConfigTidyRoletagBlacklistRead(req *logical.Request, data *framework.FieldData) (*logical.Response, error) { clientConfig, err := b.lockedConfigTidyRoleTags(req.Storage) if err != nil { return nil, err } if clientConfig == nil { return nil, nil } return &logical.Response{ Data: structs.New(clientConfig).Map(), }, nil }
func (b *backend) pathCRLRead( req *logical.Request, data *framework.FieldData) (*logical.Response, error) { config, err := b.CRL(req.Storage) if err != nil { return nil, err } if config == nil { return nil, nil } return &logical.Response{ Data: structs.New(config).Map(), }, nil }
// IsValid asserts the JobFindOptions instance has one // and only one value set to a non-zero value. // // This method is particularly useful to check a JobFindOptions // instance before passing it to JobsService.Find method. func (jfo *JobFindOptions) IsValid() bool { s := structs.New(jfo) f := s.Fields() nonZeroValues := 0 for _, field := range f { if !field.IsZero() { nonZeroValues += 1 } } return nonZeroValues == 0 || nonZeroValues == 1 }
func (b *backend) pathRoleRead( req *logical.Request, data *framework.FieldData) (*logical.Response, error) { role, err := getRole(req.Storage, data.Get("name").(string)) if err != nil { return nil, err } if role == nil { return nil, nil } return &logical.Response{ Data: structs.New(role).Map(), }, nil }
func (context *clientContext) sendInitialize() error { hostname, _ := os.Hostname() titleVars := ContextVars{ //Command: strings.Join(context.app.command, " "), //Pid: context.command.Process.Pid, Hostname: hostname, RemoteAddr: context.request.RemoteAddr, } if context.command != nil { titleVars.Command = strings.Join(context.app.command, " ") titleVars.Pid = context.command.Process.Pid } else { titleVars.Command = "exec2hterm" titleVars.Pid = syscall.Getpid() } titleBuffer := new(bytes.Buffer) if err := context.app.titleTemplate.Execute(titleBuffer, titleVars); err != nil { return err } if err := context.write(append([]byte{SetWindowTitle}, titleBuffer.Bytes()...)); err != nil { return err } prefStruct := structs.New(context.app.options.Preferences) prefMap := prefStruct.Map() htermPrefs := make(map[string]interface{}) for key, value := range prefMap { rawKey := prefStruct.Field(key).Tag("hcl") if _, ok := context.app.options.RawPreferences[rawKey]; ok { htermPrefs[strings.Replace(rawKey, "_", "-", -1)] = value } } prefs, err := json.Marshal(htermPrefs) if err != nil { return err } if err := context.write(append([]byte{SetPreferences}, prefs...)); err != nil { return err } if context.app.options.EnableReconnect { reconnect, _ := json.Marshal(context.app.options.ReconnectTime) if err := context.write(append([]byte{SetReconnect}, reconnect...)); err != nil { return err } } return nil }