mirror of
https://codeberg.org/scip/ts.git
synced 2026-08-24 06:44:19 +02:00
64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
|
|
package runexpr
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/expr-lang/expr"
|
||
|
|
)
|
||
|
|
|
||
|
|
type Env struct {
|
||
|
|
Now func() time.Time
|
||
|
|
Dur, D func(string) time.Duration
|
||
|
|
Strf func(any, ...any) string
|
||
|
|
Diff func(a, b time.Time) time.Duration
|
||
|
|
Add func(time.Time, time.Duration) time.Time
|
||
|
|
Time, T func(string, ...string) time.Time
|
||
|
|
Human func(time.Duration) string
|
||
|
|
Years, Days, Hours, Minutes, Seconds func(time.Duration) float64
|
||
|
|
Clock func(time.Time) string
|
||
|
|
Unix func(time.Time) int64
|
||
|
|
TZ func(time.Time, any) time.Time
|
||
|
|
}
|
||
|
|
|
||
|
|
func RunExpr(code string) {
|
||
|
|
env := Env{
|
||
|
|
Now: time.Now,
|
||
|
|
Dur: parseDuration,
|
||
|
|
D: parseDuration,
|
||
|
|
Strf: strfTime,
|
||
|
|
Diff: timeDiff,
|
||
|
|
Add: timeAdd,
|
||
|
|
Time: newTime,
|
||
|
|
T: newTime,
|
||
|
|
Human: formatDuration,
|
||
|
|
Years: toYears,
|
||
|
|
Days: toDays,
|
||
|
|
Hours: toHours,
|
||
|
|
Minutes: toMinutes,
|
||
|
|
Seconds: toSeconds,
|
||
|
|
Clock: toClock,
|
||
|
|
Unix: toUnix,
|
||
|
|
TZ: toTZ,
|
||
|
|
}
|
||
|
|
|
||
|
|
options := []expr.Option{
|
||
|
|
expr.Env(Env{}),
|
||
|
|
expr.Operator("-", "Diff"), // custom operator to diff two time.Time's
|
||
|
|
expr.Operator("+", "Add"), // custom operator to add time.Duration to a time.Time
|
||
|
|
}
|
||
|
|
|
||
|
|
program, err := expr.Compile(code, options...)
|
||
|
|
if err != nil {
|
||
|
|
fmt.Printf("%v", err)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
output, err := expr.Run(program, env)
|
||
|
|
if err != nil {
|
||
|
|
panic(err)
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Println(output)
|
||
|
|
}
|