parseCLISchedule parses a schedule in the format HH:MM{AM|PM} [DOW] [LOCATION]
(parts ...string)
| 101 | |
| 102 | // parseCLISchedule parses a schedule in the format HH:MM{AM|PM} [DOW] [LOCATION] |
| 103 | func parseCLISchedule(parts ...string) (*cron.Schedule, error) { |
| 104 | // If the user was careful and quoted the schedule, un-quote it. |
| 105 | // In the case that only time was specified, this will be a no-op. |
| 106 | if len(parts) == 1 { |
| 107 | parts = strings.Fields(parts[0]) |
| 108 | } |
| 109 | var loc *time.Location |
| 110 | dayOfWeek := "*" |
| 111 | t, err := parseTime(parts[0]) |
| 112 | if err != nil { |
| 113 | return nil, err |
| 114 | } |
| 115 | hour, minute := t.Hour(), t.Minute() |
| 116 | |
| 117 | // Any additional parts get ignored. |
| 118 | switch len(parts) { |
| 119 | case 3: |
| 120 | dayOfWeek = parts[1] |
| 121 | loc, err = time.LoadLocation(parts[2]) |
| 122 | if err != nil { |
| 123 | _, err = time.Parse("MST", parts[2]) |
| 124 | if err == nil { |
| 125 | return nil, errUnsupportedTimezone |
| 126 | } |
| 127 | return nil, xerrors.Errorf("Invalid timezone %q specified: a valid IANA timezone is required", parts[2]) |
| 128 | } |
| 129 | case 2: |
| 130 | // Did they provide day-of-week or location? |
| 131 | if maybeLoc, err := time.LoadLocation(parts[1]); err != nil { |
| 132 | // Assume day-of-week. |
| 133 | dayOfWeek = parts[1] |
| 134 | } else { |
| 135 | loc = maybeLoc |
| 136 | } |
| 137 | case 1: // already handled |
| 138 | default: |
| 139 | return nil, errInvalidScheduleFormat |
| 140 | } |
| 141 | |
| 142 | // If location was not specified, attempt to automatically determine it as a last resort. |
| 143 | if loc == nil { |
| 144 | loc, err = tz.TimezoneIANA() |
| 145 | if err != nil { |
| 146 | loc = time.UTC |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | sched, err := cron.Weekly(fmt.Sprintf( |
| 151 | "CRON_TZ=%s %d %d * * %s", |
| 152 | loc.String(), |
| 153 | minute, |
| 154 | hour, |
| 155 | dayOfWeek, |
| 156 | )) |
| 157 | if err != nil { |
| 158 | // This will either be an invalid dayOfWeek or an invalid timezone. |
| 159 | return nil, xerrors.Errorf("Invalid schedule: %w", err) |
| 160 | } |