Skip to content

Commit

Permalink
refactor: add Now() to SyncModel
Browse files Browse the repository at this point in the history
  • Loading branch information
danroc committed Apr 26, 2022
1 parent f4f5764 commit c41d28b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 9 deletions.
5 changes: 2 additions & 3 deletions cmd/htp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down
4 changes: 4 additions & 0 deletions pkg/htp/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 5 additions & 6 deletions pkg/htp/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit c41d28b

Please # to comment.