Skip to content

Commit

Permalink
time: per-thread time.now() function
Browse files Browse the repository at this point in the history
  • Loading branch information
ash2k committed Oct 29, 2023
1 parent 2232540 commit 92e53c1
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion lib/time/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,25 @@ var Module = &starlarkstruct.Module{
// NowFunc is a function that generates the current time. Intentionally exported
// so that it can be overridden, for example by applications that require their
// Starlark scripts to be fully deterministic.
//
// Deprecated: use SetNow() to set per-thread clock.
var NowFunc = time.Now

const contextKey = "time.Now"

// SetNow associates with the specified Starlark thread a function that generates the current time.
// Can be used for example by applications that require their
// Starlark scripts to be fully deterministic.
func SetNow(thread *starlark.Thread, nowFunc func() time.Time) {
thread.SetLocal(contextKey, nowFunc)
}

// Now returns the function to generate the current time previously associated with this thread.
func Now(thread *starlark.Thread) func() time.Time {
nowFunc, _ := thread.Local(contextKey).(func() time.Time)
return nowFunc
}

func parseDuration(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var d Duration
err := starlark.UnpackPositionalArgs("parse_duration", args, kwargs, 1, &d)
Expand Down Expand Up @@ -129,7 +146,11 @@ func fromTimestamp(thread *starlark.Thread, _ *starlark.Builtin, args starlark.T
}

func now(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
return Time(NowFunc()), nil
nowFunc := Now(thread)
if nowFunc == nil {
nowFunc = NowFunc
}
return Time(nowFunc()), nil
}

// Duration is a Starlark representation of a duration.
Expand Down

0 comments on commit 92e53c1

Please sign in to comment.