Skip to content

go-universal/revision

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Go Revision Library

GitHub Tag Go Reference License Go Report Card Contributors Issues

A Go library for tracking and comparing struct revisions. It provides a simple interface to detect changes between two struct instances, with support for field inclusion/exclusion and easy integration into your projects.

Features

  • Compare two structs and get a list of changed fields
  • Ignore unexported fields automatically
  • Include or exclude specific fields from comparison
  • Simple API for checking if structs are identical or changed

Installation

go get github.com/go-universal/revision

Usage

Basic Example

package main

import (
    "fmt"
    "github.com/go-universal/revision"
)

type User struct {
    ID    int
    Name  string
    Email string
    age   int // unexported, will be ignored
}

func main() {
    oldUser := User{ID: 1, Name: "Alice", Email: "alice@example.com", age: 30}
    newUser := User{ID: 1, Name: "Alice Smith", Email: "alice.smith@example.com", age: 31}

    rev := revision.NewRevision(oldUser, newUser)

    if !rev.IsValid() {
        panic("Invalid revision: structs must be of the same type")
    }

    changes := rev.Changes()
    for _, c := range changes {
        fmt.Printf("Field: %s, Old: %v, New: %v\n", c.Field, c.OldValue, c.NewValue)
    }

    fmt.Println("IsSame:", rev.IsSame())     // false
    fmt.Println("IsChanged:", rev.IsChanged()) // true
}

Including or Excluding Fields

You can specify which fields to include or exclude in the comparison:

rev := revision.NewRevision(
    oldUser,
    newUser,
    revision.WithIncludeFields("Name"), // Only compare the Name field
)

// Or exclude specific fields
rev = revision.NewRevision(
    oldUser,
    newUser,
    revision.WithExcludeFields("Email"), // Compare all except Email
)

API

Revision Interface

  • IsValid() bool β€” Returns true if both structs are valid and of the same type.
  • Changes() Changes β€” Returns a slice of changed fields (see below).
  • IsSame() bool β€” Returns true if there are no changes.
  • IsChanged() bool β€” Returns true if there are any changes.

Change Struct

  • Field string β€” The name of the changed field
  • OldValue any β€” The old value
  • NewValue any β€” The new value

Changes Methods

  • Contains(field string) bool β€” Returns true if the field is in the changes
  • Find(field string) (any, any, bool) β€” Returns old/new values and true if found
  • Length() int β€” Number of changed fields
  • Fields() []string β€” List of changed field names

License

This project is licensed under the ISC License. See the LICENSE file for details.

About

πŸ”Ž Detect changes between Go structs with flexible field filtering.

Topics

Resources

License

Stars

Watchers

Forks

Languages