ApplyArguments takes the given arguments and uses them to satisfy a field parameter. If a single argument and no formatting pattern are given the single argument is used as the field value. Otherwise the arguments will be used as arguments to Printf with the formatting string as the pattern.
(field *pb.Field, args ...*pb.Argument)
| 79 | // formatting pattern are given the single argument is used as the field value. Otherwise the arguments will be used as |
| 80 | // arguments to Printf with the formatting string as the pattern. |
| 81 | func ApplyArguments(field *pb.Field, args ...*pb.Argument) error { |
| 82 | if field == nil { |
| 83 | return errors.New("field was nil") |
| 84 | } else if field.GetParam() == nil { |
| 85 | return fmt.Errorf("field %s does not have a parameter", field.Key) |
| 86 | } else if len(args) < 1 && field.GetParam().GetDefault() == nil { |
| 87 | return errors.New("an argument must be specified if no default is given") |
| 88 | } else if len(args) < 1 { |
| 89 | return applyDefault(field) |
| 90 | } else if len(args) == 1 && len(field.GetParam().Pattern) == 0 { |
| 91 | return simpleArgApply(field, args[0]) |
| 92 | } else if len(args) > 1 && len(field.GetParam().Pattern) == 0 { |
| 93 | return errors.New("may only use multiple arguments if a string template is provided") |
| 94 | } |
| 95 | |
| 96 | argVals := make([]interface{}, len(args)) |
| 97 | for i, v := range args { |
| 98 | switch val := v.GetValue().(type) { |
| 99 | case *pb.Argument_Number: |
| 100 | argVals[i] = val.Number |
| 101 | case *pb.Argument_Str: |
| 102 | argVals[i] = val.Str |
| 103 | case *pb.Argument_Boolean: |
| 104 | argVals[i] = val.Boolean |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | val := fmt.Sprintf(field.GetParam().Pattern, argVals...) |
| 109 | field.Value = &pb.Field_Str{Str: val} |
| 110 | return nil |
| 111 | } |
| 112 | |
| 113 | // ParameterFields returns the fields with parameters contained within a Document. |
| 114 | func ParameterFields(docs map[string]*pb.Document) map[string]*pb.Field { |