MCPcopy
hub / github.com/robfig/cron / normalizeFields

Function normalizeFields

parser.go:160–215  ·  view source on GitHub ↗

normalizeFields takes a subset set of the time fields and returns the full set with defaults (zeroes) populated for unset fields. As part of performing this function, it also validates that the provided fields are compatible with the configured options.

(fields []string, options ParseOption)

Source from the content-addressed store, hash-verified

158// As part of performing this function, it also validates that the provided
159// fields are compatible with the configured options.
160func normalizeFields(fields []string, options ParseOption) ([]string, error) {
161 // Validate optionals & add their field to options
162 optionals := 0
163 if options&SecondOptional > 0 {
164 options |= Second
165 optionals++
166 }
167 if options&DowOptional > 0 {
168 options |= Dow
169 optionals++
170 }
171 if optionals > 1 {
172 return nil, fmt.Errorf("multiple optionals may not be configured")
173 }
174
175 // Figure out how many fields we need
176 max := 0
177 for _, place := range places {
178 if options&place > 0 {
179 max++
180 }
181 }
182 min := max - optionals
183
184 // Validate number of fields
185 if count := len(fields); count < min || count > max {
186 if min == max {
187 return nil, fmt.Errorf("expected exactly %d fields, found %d: %s", min, count, fields)
188 }
189 return nil, fmt.Errorf("expected %d to %d fields, found %d: %s", min, max, count, fields)
190 }
191
192 // Populate the optional field if not provided
193 if min < max && len(fields) == min {
194 switch {
195 case options&DowOptional > 0:
196 fields = append(fields, defaults[5]) // TODO: improve access to default
197 case options&SecondOptional > 0:
198 fields = append([]string{defaults[0]}, fields...)
199 default:
200 return nil, fmt.Errorf("unknown optional field")
201 }
202 }
203
204 // Populate all fields not part of options with their defaults
205 n := 0
206 expandedFields := make([]string, len(places))
207 copy(expandedFields, defaults)
208 for i, place := range places {
209 if options&place > 0 {
210 expandedFields[i] = fields[n]
211 n++
212 }
213 }
214 return expandedFields, nil
215}
216
217var standardParser = NewParser(

Callers 3

TestNormalizeFieldsFunction · 0.85
ParseMethod · 0.85

Calls

no outgoing calls

Tested by 2

TestNormalizeFieldsFunction · 0.68