identity: rework mutation

Michael Muré created

Change summary

cache/identity_cache.go |  4 ++--
identity/identity.go    | 23 +++++++++++++++++++++--
identity/version.go     | 12 ++++++++++--
3 files changed, 33 insertions(+), 6 deletions(-)

Detailed changes

cache/identity_cache.go 🔗

@@ -21,8 +21,8 @@ func (i *IdentityCache) notifyUpdated() error {
 	return i.repoCache.identityUpdated(i.Identity.Id())
 }
 
-func (i *IdentityCache) AddVersion(version *identity.Version) error {
-	i.Identity.AddVersion(version)
+func (i *IdentityCache) Mutate(f func(identity.VersionMutator) identity.VersionMutator) error {
+	i.Identity.Mutate(f)
 	return i.notifyUpdated()
 }
 

identity/identity.go 🔗

@@ -5,6 +5,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"os"
+	"reflect"
 	"strings"
 	"time"
 
@@ -271,8 +272,26 @@ func IsUserIdentitySet(repo repository.Repo) (bool, error) {
 	return len(configs) == 1, nil
 }
 
-func (i *Identity) AddVersion(version *Version) {
-	i.versions = append(i.versions, version)
+// Mutate allow to create a new version of the Identity
+func (i *Identity) Mutate(f func(orig VersionMutator) VersionMutator) {
+	orig := VersionMutator{
+		Name:      i.Name(),
+		Email:     i.Email(),
+		Login:     i.Login(),
+		AvatarUrl: i.AvatarUrl(),
+		Keys:      i.Keys(),
+	}
+	mutated := f(orig)
+	if reflect.DeepEqual(orig, mutated) {
+		return
+	}
+	i.versions = append(i.versions, &Version{
+		name:      mutated.Name,
+		email:     mutated.Email,
+		login:     mutated.Login,
+		avatarURL: mutated.AvatarUrl,
+		keys:      mutated.Keys,
+	})
 }
 
 // Write the identity into the Repository. In particular, this ensure that

identity/version.go 🔗

@@ -24,8 +24,8 @@ type Version struct {
 	unixTime int64
 
 	name      string
-	email     string
-	login     string
+	email     string // TODO: remove ? keep and use metadata for bridges ?
+	login     string // TODO: remove
 	avatarURL string
 
 	// The set of keys valid at that time, from this version onward, until they get removed
@@ -60,6 +60,14 @@ type VersionJSON struct {
 	Metadata  map[string]string `json:"metadata,omitempty"`
 }
 
+type VersionMutator struct {
+	Name      string
+	Email     string
+	Login     string
+	AvatarUrl string
+	Keys      []Key
+}
+
 func (v *Version) MarshalJSON() ([]byte, error) {
 	return json.Marshal(VersionJSON{
 		FormatVersion: formatVersion,