Debian Codegraph @

lib/time/time.go

raw
1 // Copyright 2021 The Bazel Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package time provides time-related constants and functions.
6 package time // import "go.starlark.net/lib/time"
7
8 import (
9 "errors"
10 "fmt"
11 "sort"
12 "time"
13
14 "go.starlark.net/starlark"
15 "go.starlark.net/starlarkstruct"
16 "go.starlark.net/syntax"
17 )
18
19 // Module time is a Starlark module of time-related functions and constants.
20 // The module defines the following functions:
21 //
22 // from_timestamp(sec, nsec) - Converts the given Unix time corresponding to the number of seconds
23 // and (optionally) nanoseconds since January 1, 1970 UTC into an object
24 // of type Time. For more details, refer to https://pkg.go.dev/time#Unix.
25 //
26 // is_valid_timezone(loc) - Reports whether loc is a valid time zone name.
27 //
28 // now() - Returns the current local time. Applications may replace this function by a deterministic one.
29 //
30 // parse_duration(d) - Parses the given duration string. For more details, refer to
31 // https://pkg.go.dev/time#ParseDuration.
32 //
33 // parse_time(x, format, location) - Parses the given time string using a specific time format and location.
34 // The expected arguments are a time string (mandatory), a time format
35 // (optional, set to RFC3339 by default, e.g. "2021-03-22T23:20:50.52Z")
36 // and a name of location (optional, set to UTC by default). For more details,
37 // refer to https://pkg.go.dev/time#Parse and https://pkg.go.dev/time#ParseInLocation.
38 //
39 // time(year, month, day, hour, minute, second, nanosecond, location) - Returns the Time corresponding to
40 // yyyy-mm-dd hh:mm:ss + nsec nanoseconds
41 // in the appropriate zone for that time
42 // in the given location. All the parameters
43 // are optional.
44 //
45 // The module also defines the following constants:
46 //
47 // nanosecond - A duration representing one nanosecond.
48 // microsecond - A duration representing one microsecond.
49 // millisecond - A duration representing one millisecond.
50 // second - A duration representing one second.
51 // minute - A duration representing one minute.
52 // hour - A duration representing one hour.
53 var Module = &starlarkstruct.Module{
54 Name: "time",
55 Members: starlark.StringDict{
56 "from_timestamp": starlark.NewBuiltin("from_timestamp", fromTimestamp),
57 "is_valid_timezone": starlark.NewBuiltin("is_valid_timezone", isValidTimezone),
58 "now": starlark.NewBuiltin("now", now),
59 "parse_duration": starlark.NewBuiltin("parse_duration", parseDuration),
60 "parse_time": starlark.NewBuiltin("parse_time", parseTime),
61 "time": starlark.NewBuiltin("time", newTime),
62
63 "nanosecond": Duration(time.Nanosecond),
64 "microsecond": Duration(time.Microsecond),
65 "millisecond": Duration(time.Millisecond),
66 "second": Duration(time.Second),
67 "minute": Duration(time.Minute),
68 "hour": Duration(time.Hour),
69 },
70 }
71
72 // NowFunc is a function that reports the current time. Intentionally exported
73 // so that it can be overridden, for example by applications that require their
74 // Starlark scripts to be fully deterministic.
75 //
76 // Deprecated: avoid updating this global variable
77 // and instead use SetNow on each thread to set its clock function.
78 var NowFunc = time.Now
79
80 const contextKey = "time.now"
81
82 // SetNow sets the thread's optional clock function.
83 // If non-nil, it will be used in preference to NowFunc when the
84 // thread requests the current time by executing a call to time.now.
85 func SetNow(thread *starlark.Thread, nowFunc func() (time.Time, error)) {
86 thread.SetLocal(contextKey, nowFunc)
87 }
88
89 // Now returns the clock function previously associated with this thread.
90 func Now(thread *starlark.Thread) func() (time.Time, error) {
91 nowFunc, _ := thread.Local(contextKey).(func() (time.Time, error))
92 return nowFunc
93 }
94
95 func parseDuration(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
96 var d Duration
97 err := starlark.UnpackPositionalArgs("parse_duration", args, kwargs, 1, &d)
98 return d, err
99 }
100
101 func isValidTimezone(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
102 var s string
103 if err := starlark.UnpackPositionalArgs("is_valid_timezone", args, kwargs, 1, &s); err != nil {
104 return nil, err
105 }
106 _, err := time.LoadLocation(s)
107 return starlark.Bool(err == nil), nil
108 }
109
110 func parseTime(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
111 var (
112 x string
113 location = "UTC"
114 format = time.RFC3339
115 )
116 if err := starlark.UnpackArgs("parse_time", args, kwargs, "x", &x, "format?", &format, "location?", &location); err != nil {
117 return nil, err
118 }
119
120 if location == "UTC" {
121 t, err := time.Parse(format, x)
122 if err != nil {
123 return nil, err
124 }
125 return Time(t), nil
126 }
127
128 loc, err := time.LoadLocation(location)
129 if err != nil {
130 return nil, err
131 }
132 t, err := time.ParseInLocation(format, x, loc)
133 if err != nil {
134 return nil, err
135 }
136 return Time(t), nil
137 }
138
139 func fromTimestamp(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
140 var (
141 sec int64
142 nsec int64 = 0
143 )
144 if err := starlark.UnpackPositionalArgs("from_timestamp", args, kwargs, 1, &sec, &nsec); err != nil {
145 return nil, err
146 }
147 return Time(time.Unix(sec, nsec)), nil
148 }
149
150 func now(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
151 nowErrFunc := Now(thread)
152 if nowErrFunc != nil {
153 t, err := nowErrFunc()
154 if err != nil {
155 return nil, err
156 }
157 return Time(t), nil
158 }
159 nowFunc := NowFunc
160 if nowFunc == nil {
161 return nil, errors.New("time.now() is not available")
162 }
163 return Time(nowFunc()), nil
164 }
165
166 // Duration is a Starlark representation of a duration.
167 type Duration time.Duration
168
169 // Assert at compile time that Duration implements Unpacker.
170 var _ starlark.Unpacker = (*Duration)(nil)
171
172 // Unpack is a custom argument unpacker
173 func (d *Duration) Unpack(v starlark.Value) error {
174 switch x := v.(type) {
175 case Duration:
176 *d = x
177 return nil
178 case starlark.String:
179 dur, err := time.ParseDuration(string(x))
180 if err != nil {
181 return err
182 }
183
184 *d = Duration(dur)
185 return nil
186 }
187
188 return fmt.Errorf("got %s, want a duration, string, or int", v.Type())
189 }
190
191 // String implements the Stringer interface.
192 func (d Duration) String() string { return time.Duration(d).String() }
193
194 // Type returns a short string describing the value's type.
195 func (d Duration) Type() string { return "time.duration" }
196
197 // Freeze renders Duration immutable. required by starlark.Value interface
198 // because duration is already immutable this is a no-op.
199 func (d Duration) Freeze() {}
200
201 // Hash returns a function of x such that Equals(x, y) => Hash(x) == Hash(y)
202 // required by starlark.Value interface.
203 func (d Duration) Hash() (uint32, error) {
204 return uint32(d) ^ uint32(int64(d)>>32), nil
205 }
206
207 // Truth reports whether the duration is non-zero.
208 func (d Duration) Truth() starlark.Bool { return d != 0 }
209
210 // Attr gets a value for a string attribute, implementing dot expression support
211 // in starlark. required by starlark.HasAttrs interface.
212 func (d Duration) Attr(name string) (starlark.Value, error) {
213 switch name {
214 case "hours":
215 return starlark.Float(time.Duration(d).Hours()), nil
216 case "minutes":
217 return starlark.Float(time.Duration(d).Minutes()), nil
218 case "seconds":
219 return starlark.Float(time.Duration(d).Seconds()), nil
220 case "milliseconds":
221 return starlark.MakeInt64(time.Duration(d).Milliseconds()), nil
222 case "microseconds":
223 return starlark.MakeInt64(time.Duration(d).Microseconds()), nil
224 case "nanoseconds":
225 return starlark.MakeInt64(time.Duration(d).Nanoseconds()), nil
226 }
227 return nil, fmt.Errorf("unrecognized %s attribute %q", d.Type(), name)
228 }
229
230 // AttrNames lists available dot expression strings. required by
231 // starlark.HasAttrs interface.
232 func (d Duration) AttrNames() []string {
233 return []string{
234 "hours",
235 "minutes",
236 "seconds",
237 "milliseconds",
238 "microseconds",
239 "nanoseconds",
240 }
241 }
242
243 // Cmp implements comparison of two Duration values. required by
244 // starlark.TotallyOrdered interface.
245 func (d Duration) Cmp(v starlark.Value, depth int) (int, error) {
246 if x, y := d, v.(Duration); x < y {
247 return -1, nil
248 } else if x > y {
249 return 1, nil
250 }
251 return 0, nil
252 }
253
254 // Binary implements binary operators, which satisfies the starlark.HasBinary
255 // interface. operators:
256 //
257 // duration + duration = duration
258 // duration + time = time
259 // duration - duration = duration
260 // duration / duration = float
261 // duration / int = duration
262 // duration / float = duration
263 // duration // duration = int
264 // duration * int = duration
265 func (d Duration) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) {
266 x := time.Duration(d)
267
268 switch op {
269 case syntax.PLUS:
270 switch y := y.(type) {
271 case Duration:
272 return Duration(x + time.Duration(y)), nil
273 case Time:
274 return Time(time.Time(y).Add(x)), nil
275 }
276
277 case syntax.MINUS:
278 switch y := y.(type) {
279 case Duration:
280 return Duration(x - time.Duration(y)), nil
281 }
282
283 case syntax.SLASH:
284 switch y := y.(type) {
285 case Duration:
286 if y == 0 {
287 return nil, fmt.Errorf("%s division by zero", d.Type())
288 }
289 return starlark.Float(x.Nanoseconds()) / starlark.Float(time.Duration(y).Nanoseconds()), nil
290 case starlark.Int:
291 if side == starlark.Right {
292 return nil, fmt.Errorf("unsupported operation")
293 }
294 i, ok := y.Int64()
295 if !ok {
296 return nil, fmt.Errorf("int value out of range (want signed 64-bit value)")
297 }
298 if i == 0 {
299 return nil, fmt.Errorf("%s division by zero", d.Type())
300 }
301 return d / Duration(i), nil
302 case starlark.Float:
303 f := float64(y)
304 if f == 0 {
305 return nil, fmt.Errorf("%s division by zero", d.Type())
306 }
307 return Duration(float64(x.Nanoseconds()) / f), nil
308 }
309
310 case syntax.SLASHSLASH:
311 switch y := y.(type) {
312 case Duration:
313 if y == 0 {
314 return nil, fmt.Errorf("%s division by zero", d.Type())
315 }
316 return starlark.MakeInt64(x.Nanoseconds() / time.Duration(y).Nanoseconds()), nil
317 }
318
319 case syntax.STAR:
320 switch y := y.(type) {
321 case starlark.Int:
322 i, ok := y.Int64()
323 if !ok {
324 return nil, fmt.Errorf("int value out of range (want signed 64-bit value)")
325 }
326 return d * Duration(i), nil
327 }
328 }
329
330 return nil, nil
331 }
332
333 // Time is a Starlark representation of a moment in time.
334 type Time time.Time
335
336 func newTime(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
337 var (
338 year, month, day, hour, min, sec, nsec int
339 loc string
340 )
341 if err := starlark.UnpackArgs("time", args, kwargs,
342 "year?", &year,
343 "month?", &month,
344 "day?", &day,
345 "hour?", &hour,
346 "minute?", &min,
347 "second?", &sec,
348 "nanosecond?", &nsec,
349 "location?", &loc,
350 ); err != nil {
351 return nil, err
352 }
353 if len(args) > 0 {
354 return nil, fmt.Errorf("time: unexpected positional arguments")
355 }
356 location, err := time.LoadLocation(loc)
357 if err != nil {
358 return nil, err
359 }
360 return Time(time.Date(year, time.Month(month), day, hour, min, sec, nsec, location)), nil
361 }
362
363 // String returns the time formatted using the format string
364 //
365 // "2006-01-02 15:04:05.999999999 -0700 MST".
366 func (t Time) String() string { return time.Time(t).Format("2006-01-02 15:04:05.999999999 -0700 MST") }
367
368 // Type returns "time.time".
369 func (t Time) Type() string { return "time.time" }
370
371 // Freeze renders time immutable. required by starlark.Value interface
372 // because Time is already immutable this is a no-op.
373 func (t Time) Freeze() {}
374
375 // Hash returns a function of x such that Equals(x, y) => Hash(x) == Hash(y)
376 // required by starlark.Value interface.
377 func (t Time) Hash() (uint32, error) {
378 return uint32(time.Time(t).UnixNano()) ^ uint32(int64(time.Time(t).UnixNano())>>32), nil
379 }
380
381 // Truth returns the truth value of an object required by starlark.Value
382 // interface.
383 func (t Time) Truth() starlark.Bool { return !starlark.Bool(time.Time(t).IsZero()) }
384
385 // Attr gets a value for a string attribute, implementing dot expression support
386 // in starlark. required by starlark.HasAttrs interface.
387 func (t Time) Attr(name string) (starlark.Value, error) {
388 switch name {
389 case "year":
390 return starlark.MakeInt(time.Time(t).Year()), nil
391 case "month":
392 return starlark.MakeInt(int(time.Time(t).Month())), nil
393 case "day":
394 return starlark.MakeInt(time.Time(t).Day()), nil
395 case "hour":
396 return starlark.MakeInt(time.Time(t).Hour()), nil
397 case "minute":
398 return starlark.MakeInt(time.Time(t).Minute()), nil
399 case "second":
400 return starlark.MakeInt(time.Time(t).Second()), nil
401 case "nanosecond":
402 return starlark.MakeInt(time.Time(t).Nanosecond()), nil
403 case "unix":
404 return starlark.MakeInt64(time.Time(t).Unix()), nil
405 case "unix_nano":
406 return starlark.MakeInt64(time.Time(t).UnixNano()), nil
407 }
408 return builtinAttr(t, name, timeMethods)
409 }
410
411 // AttrNames lists available dot expression strings for time. required by
412 // starlark.HasAttrs interface.
413 func (t Time) AttrNames() []string {
414 return append(builtinAttrNames(timeMethods),
415 "year",
416 "month",
417 "day",
418 "hour",
419 "minute",
420 "second",
421 "nanosecond",
422 "unix",
423 "unix_nano",
424 )
425 }
426
427 // Cmp implements comparison of two Time values. Required by
428 // starlark.TotallyOrdered interface.
429 func (t Time) Cmp(yV starlark.Value, depth int) (int, error) {
430 x := time.Time(t)
431 y := time.Time(yV.(Time))
432 if x.Before(y) {
433 return -1, nil
434 } else if x.After(y) {
435 return 1, nil
436 }
437 return 0, nil
438 }
439
440 // Binary implements binary operators, which satisfies the starlark.HasBinary
441 // interface
442 //
443 // time + duration = time
444 // time - duration = time
445 // time - time = duration
446 func (t Time) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) {
447 x := time.Time(t)
448
449 switch op {
450 case syntax.PLUS:
451 switch y := y.(type) {
452 case Duration:
453 return Time(x.Add(time.Duration(y))), nil
454 }
455 case syntax.MINUS:
456 switch y := y.(type) {
457 case Duration:
458 return Time(x.Add(time.Duration(-y))), nil
459 case Time:
460 // time - time = duration
461 return Duration(x.Sub(time.Time(y))), nil
462 }
463 }
464
465 return nil, nil
466 }
467
468 var timeMethods = map[string]builtinMethod{
469 "in_location": timeIn,
470 "format": timeFormat,
471 }
472
473 func timeFormat(fnname string, recV starlark.Value, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
474 var x string
475 if err := starlark.UnpackPositionalArgs("format", args, kwargs, 1, &x); err != nil {
476 return nil, err
477 }
478
479 recv := time.Time(recV.(Time))
480 return starlark.String(recv.Format(x)), nil
481 }
482
483 func timeIn(fnname string, recV starlark.Value, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
484 var x string
485 if err := starlark.UnpackPositionalArgs("in_location", args, kwargs, 1, &x); err != nil {
486 return nil, err
487 }
488 loc, err := time.LoadLocation(x)
489 if err != nil {
490 return nil, err
491 }
492
493 recv := time.Time(recV.(Time))
494 return Time(recv.In(loc)), nil
495 }
496
497 type builtinMethod func(fnname string, recv starlark.Value, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error)
498
499 func builtinAttr(recv starlark.Value, name string, methods map[string]builtinMethod) (starlark.Value, error) {
500 method := methods[name]
501 if method == nil {
502 return nil, nil // no such method
503 }
504
505 // Allocate a closure over 'method'.
506 impl := func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
507 return method(b.Name(), b.Receiver(), args, kwargs)
508 }
509 return starlark.NewBuiltin(name, impl).BindReceiver(recv), nil
510 }
511
512 func builtinAttrNames(methods map[string]builtinMethod) []string {
513 names := make([]string, 0, len(methods))
514 for name := range methods {
515 names = append(names, name)
516 }
517 sort.Strings(names)
518 return names
519 }