Skip to content
Snippets Groups Projects
Select Git revision
  • a0efeb84938bc627b96890ecdb7478625c82b70f
  • main default protected
  • 1-mage-run-does-not-stop-containers
  • v0.26.0
  • v0.25.0
  • v0.24.0
  • v0.23.0
  • v0.22.0
  • v0.21.0
  • v0.20.0
  • v0.19.0
  • v0.18.0
  • v0.17.0
  • v0.16.0
  • v0.15.0
  • v0.14.0
  • v0.13.0
  • v0.12.0
  • v0.11.0
  • v0.10.0
  • v0.9.0
  • v0.8.0
  • v0.7.0
23 results

README.md

Blame
  • audit.go 9.35 KiB
    package audit
    
    import (
    	"encoding/json"
    	"reflect"
    	"regexp"
    	"strconv"
    	"strings"
    
    	"github.com/r3labs/diff/v2"
    	"gitlab.com/uafrica/go-utils/reflection"
    	"gitlab.com/uafrica/go-utils/string_utils"
    )
    
    type FieldChange struct {
    	From interface{} `json:"change_from"`
    	To   interface{} `json:"change_to"`
    }
    
    func GetChanges(original interface{}, new interface{}) (map[string]interface{}, error) {
    	changes := map[string]interface{}{}
    	changelog, err := diff.Diff(original, new)
    	if err != nil {
    		return changes, err
    	}
    
    	for _, change := range changelog {
    
    		if len(change.Path) == 1 {
    			// Root object change
    			field := ToSnakeCase(change.Path[0])
    			changes[field] = FieldChange{
    				From: change.From,
    				To:   change.To,
    			}
    		} else if len(change.Path) == 2 {
    			// Child object changed
    			// ["Account", "ID"]
    			// 0 = Object
    			// 1 = field
    
    			ChildObjectChanges(changes, change.Path[0], change.Path[1], change.From, change.To)
    
    		} else if len(change.Path) >= 3 {
    			// Array of objects
    			// ["Parcel", "0", "ActualWeight"]
    			// 0 = Object
    			// 1 = Index of object
    			// 2 = field
    
    			objectKey := ToSnakeCase(change.Path[0])
    			indexString := change.Path[1]
    
    			if !string_utils.IsNumericString(indexString) {
    				// Not an array, but a deeper nested object
    				ChildObjectChanges(changes, change.Path[len(change.Path)-2], change.Path[len(change.Path)-1], change.From, change.To)
    				continue
    			}
    
    			index, _ := string_utils.StringToInt64(indexString)
    			field := ToSnakeCase(change.Path[2])
    
    			arrayObject, present := changes[objectKey]
    			if present {
    				if arrayOfObjects, ok := arrayObject.([]map[string]interface{}); ok {
    					if len(arrayOfObjects) > int(index) {
    						// Add field to existing object in array
    						object := arrayOfObjects[index]
    						object[field] = FieldChange{
    							From: change.From,