From c41d28b914f551b79f18074156e6118792f131c5 Mon Sep 17 00:00:00 2001 From: Daniel Rocha Date: Wed, 27 Apr 2022 00:06:53 +0200 Subject: [PATCH] refactor: add `Now()` to `SyncModel` --- cmd/htp/main.go | 5 ++--- pkg/htp/model.go | 4 ++++ pkg/htp/service.go | 11 +++++------ 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/cmd/htp/main.go b/cmd/htp/main.go index 55f9f83..ad9cd70 100644 --- a/cmd/htp/main.go +++ b/cmd/htp/main.go @@ -52,14 +52,13 @@ func buildRootCommand() *cobra.Command { } if date { - now := time.Now().Add(time.Duration(-model.Offset())) - fmt.Printf("%s\n", now.Format(format)) + fmt.Printf("%s\n", model.Now().Format(format)) } else { fmt.Printf("%+.3f\n", -model.Offset().Sec()) } if sync { - if err := htp.SyncSystem(model.Offset()); err != nil { + if err := htp.SyncSystem(model); err != nil { return fmt.Errorf("cannot set system clock: %w", err) } } diff --git a/pkg/htp/model.go b/pkg/htp/model.go index c3de83d..89a141d 100644 --- a/pkg/htp/model.go +++ b/pkg/htp/model.go @@ -87,6 +87,10 @@ func (s *SyncModel) Sleep() { time.Sleep(s.Delay(now)) } +func (s *SyncModel) Now() time.Time { + return time.Now().Add(time.Duration(-s.Offset())) +} + func min(a, b NanoSec) NanoSec { if a < b { return a diff --git a/pkg/htp/service.go b/pkg/htp/service.go index 82a266b..833b1e0 100644 --- a/pkg/htp/service.go +++ b/pkg/htp/service.go @@ -48,20 +48,19 @@ func Sync(client *SyncClient, model *SyncModel, trace *SyncTrace) error { return nil } -func SyncSystem(offset NanoSec) error { +func SyncSystem(model *SyncModel) error { switch runtime.GOOS { case "windows": - arg := fmt.Sprintf("Set-Date -Adjust $([TimeSpan]::FromSeconds(%+.3f))", -offset.Sec()) + arg := fmt.Sprintf("Set-Date -Adjust $([TimeSpan]::FromSeconds(%+.3f))", -model.Offset().Sec()) return exec.Command("powershell", "-Command", arg).Run() case "linux": - arg := fmt.Sprintf("%+.3f seconds", -offset.Sec()) + arg := fmt.Sprintf("%+.3f seconds", -model.Offset().Sec()) return exec.Command("date", "-s", arg).Run() case "darwin": - now := time.Now().Add(time.Duration(-offset)) - arg := now.Add(time.Second).Format(macosFormat) - sleep := time.Duration(int(time.Second) - now.Nanosecond()) + arg := model.Now().Add(time.Second).Format(macosFormat) + sleep := time.Duration(int(time.Second) - model.Now().Nanosecond()) time.Sleep(sleep) return exec.Command("date", arg).Run()