From b833bceb393bd0b7e8ee010e7d5cd8be3be370a0 Mon Sep 17 00:00:00 2001 From: Jeff Carr Date: Fri, 15 Nov 2024 18:12:17 -0600 Subject: [PATCH] Package Age() Update() Append() --- packages.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/packages.go b/packages.go index aeee7ea..fd21396 100644 --- a/packages.go +++ b/packages.go @@ -8,6 +8,9 @@ import ( "os" "sort" sync "sync" + "time" + + timestamppb "google.golang.org/protobuf/types/known/timestamppb" ) // bad global lock until I figure out some other plan @@ -81,14 +84,50 @@ func (r *Packages) Append(newP *Package) bool { } } - r.Packages = append(r.Packages, newP) + r.Packages = append(r.Packages, newP) return true } +// Update version and timestamp. +// returns (ok, changed) +func (r *Packages) Update(newP *Package) (bool, bool) { + lock.Lock() + defer lock.Unlock() + + var found *Package + for _, p := range r.Packages { + if p.Name == newP.Name { + found = p + } + } + if found == nil { + // r.Append(newP) // update here? + return false, true + } + + var changed bool = false + if newP.Version != found.Version { + changed = true + found.Version = newP.Version + } + + now := time.Now() + found.Laststamp = timestamppb.New(now) + + r.Packages = append(r.Packages, newP) + return true, changed +} + +// returns time.Duration since last Update() +func (r *Package) Age(newP *Package) time.Duration { + t := time.Since(r.Laststamp.AsTime()) + return t +} + // find a package by name func (r *Packages) FindByName(name string) *Package { - lock.Lock() - defer lock.Unlock() + lock.RLock() + defer lock.RUnlock() for _, p := range r.Packages { if p.Name == name { @@ -99,6 +138,13 @@ func (r *Packages) FindByName(name string) *Package { return nil } +func (r *Packages) Len() int { + lock.RLock() + defer lock.RUnlock() + + return len(r.Packages) +} + type ByName []*Package func (a ByName) Len() int { return len(a) }