go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gce/api/config/v1/timeofday.go (about)

     1  // Copyright 2019 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package config
    16  
    17  import (
    18  	"regexp"
    19  	"strconv"
    20  	"time"
    21  
    22  	"google.golang.org/genproto/googleapis/type/dayofweek"
    23  
    24  	"go.chromium.org/luci/common/errors"
    25  	"go.chromium.org/luci/config/validation"
    26  )
    27  
    28  // timeRegex is the regular expression valid time strings must match.
    29  const timeRegex = "^([0-2]?[0-9]):([0-6][0-9])$"
    30  
    31  // toTime returns the time.Time representation of the time referenced by this
    32  // time of day.
    33  func (t *TimeOfDay) toTime() (time.Time, error) {
    34  	now := time.Time{}
    35  	loc, err := time.LoadLocation(t.GetLocation())
    36  	if err != nil {
    37  		return now, errors.Reason("invalid location").Err()
    38  	}
    39  	now = now.In(loc)
    40  	// Decompose the time into a slice of [time, <hour>, <minute>].
    41  	m := regexp.MustCompile(timeRegex).FindStringSubmatch(t.GetTime())
    42  	if len(m) != 3 {
    43  		return now, errors.Reason("time must match regex %q", timeRegex).Err()
    44  	}
    45  	hr, err := strconv.Atoi(m[1])
    46  	if err != nil || hr > 23 {
    47  		return now, errors.Reason("time must not exceed 23:xx").Err()
    48  	}
    49  	min, err := strconv.Atoi(m[2])
    50  	if err != nil || min > 59 {
    51  		return now, errors.Reason("time must not exceed xx:59").Err()
    52  	}
    53  	return time.Date(now.Year(), now.Month(), now.Day(), hr, min, 0, 0, loc), nil
    54  }
    55  
    56  // Validate validates this time of day.
    57  func (t *TimeOfDay) Validate(c *validation.Context) {
    58  	if t.GetDay() == dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED {
    59  		c.Errorf("day must be specified")
    60  	}
    61  	_, err := t.toTime()
    62  	if err != nil {
    63  		c.Errorf("%s", err)
    64  	}
    65  }